Fix comment count being broken for first comment

This commit is contained in:
2025-11-06 20:35:25 +02:00
parent 7e7231b514
commit bb3900d23b

View File

@@ -213,13 +213,21 @@ export default function Post() {
const onAddComment = async (postId: number, commentText: string) => { const onAddComment = async (postId: number, commentText: string) => {
if (!user || !paginatedComments) return; if (!user) return;
const res = await API.postComment(postId, commentText, user); const res = await API.postComment(postId, commentText, user);
if (!res.ok) { if (!res.ok) {
alert("Failed to add comment"); alert("Failed to add comment");
return; return;
} }
const newComment: Comment = await res.json(); const newComment: Comment = await res.json();
// Refetch comments if this is the first one.
if (!paginatedComments || paginatedComments.totalCount === 0) {
const comments = await API.fetchCommentsByPostId(idNum, 1);
setPaginatedComments(comments);
setCurrentCommentPage(1);
return;
}
const totalPages = Math.ceil((paginatedComments.totalCount + 1) / paginatedComments.pageSize); const totalPages = Math.ceil((paginatedComments.totalCount + 1) / paginatedComments.pageSize);
if (currentCommentPage !== totalPages) { if (currentCommentPage !== totalPages) {
@@ -232,7 +240,7 @@ export default function Post() {
return { return {
...prev, ...prev,
items: [...prev.items, newComment], items: [...prev.items, newComment],
total: prev.totalCount + 1 totalCount: prev.totalCount + 1
}; };
} else { } else {
// This case is unlikely if totalPages is calculated correctly, but as a fallback, we refetch. // This case is unlikely if totalPages is calculated correctly, but as a fallback, we refetch.
@@ -259,10 +267,13 @@ export default function Post() {
setPaginatedComments(prev => { setPaginatedComments(prev => {
if (!prev) return null; if (!prev) return null;
const newItems = prev.items.filter(c => c.id !== commentId); const newItems = prev.items.filter(c => c.id !== commentId);
const newTotalCount = prev.totalCount - 1;
if (newItems.length === 0 && currentCommentPage > 1) { if (newItems.length === 0 && currentCommentPage > 1) {
setCurrentCommentPage(currentCommentPage - 1); setCurrentCommentPage(currentCommentPage - 1);
return { ...prev, items: newItems, totalCount: newTotalCount };
} }
return { ...prev, items: newItems, total: prev.totalCount - 1 }; return { ...prev, items: newItems, totalCount: newTotalCount };
}); });
}; };