local updation of articles too after article creation or modification

This commit is contained in:
2025-11-15 18:18:40 +05:30
parent 333f931cff
commit c0bcd0e3e4

View File

@@ -12,6 +12,19 @@ export const ArticleProvider: React.FC<{ children: React.ReactNode }> = ({ child
const [error, setError] = useState<string | null>(null);
const { token, currentUser } = useAuth();
const upsertArticleInList = (updated: ArticleModel) => {
setArticles(prev => {
const exists = prev.some(a => a._id === updated._id);
if (exists) {
// UPDATE → replace item
return prev.map(a => (a._id === updated._id ? updated : a));
} else {
// CREATE → append to top
return [updated, ...prev];
}
});
};
/** 🔹 Author IDs must be strings for API, so we normalize here */
const normalizeArticleForApi = (article: Partial<ArticleModel>) => {
// Extract existing authors as a list of IDs (string[])
@@ -60,6 +73,7 @@ export const ArticleProvider: React.FC<{ children: React.ReactNode }> = ({ child
setError(null);
const res = await api.put<ArticleModel>(`/articles/${articleData._id}`, normalizedArticleData);
upsertArticleInList(res.data);
return res.data;
} catch (err: any) {
console.error('Article update failed:', err);
@@ -82,6 +96,7 @@ export const ArticleProvider: React.FC<{ children: React.ReactNode }> = ({ child
setError(null);
const res = await api.post<ArticleModel>(`/articles`, normalizedArticleData);
upsertArticleInList(res.data);
return res.data;
} catch (err: any) {
console.error('Article create failed:', err);