local updation of articles too after article creation or modification
This commit is contained in:
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user