making sure currentUser is in the list of authors for article

This commit is contained in:
2025-11-15 17:34:01 +05:30
parent 763629faa1
commit 3960de3ecb

View File

@@ -10,15 +10,25 @@ export const ArticleProvider: React.FC<{ children: React.ReactNode }> = ({ child
const [articles, setArticles] = useState<ArticleModel[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const { token } = useAuth();
const { token, currentUser } = useAuth();
/** 🔹 Author IDs must be strings for API, so we normalize here */
const normalizeArticleForApi = (article: Partial<ArticleModel>) => ({
...article,
authors: (article.authors ?? []).map(a =>
a._id
),
});
const normalizeArticleForApi = (article: Partial<ArticleModel>) => {
// Extract existing authors as a list of IDs (string[])
const existingIds = (article.authors ?? []).map(a =>
typeof a === "string" ? a : a._id
);
// Inject currentUser if missing
const allAuthorIds = currentUser?._id
? Array.from(new Set([...existingIds, currentUser._id])) // dedupe
: existingIds;
return {
...article,
authors: allAuthorIds,
};
};
/** 🔹 Fetch articles (JWT automatically attached by api.ts interceptor) */
const fetchArticles = async () => {