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,7 +213,7 @@ export default function Post() {
const onAddComment = async (postId: number, commentText: string) => {
if (!user || !paginatedComments) return;
if (!user) return;
const res = await API.postComment(postId, commentText, user);
if (!res.ok) {
alert("Failed to add comment");
@@ -221,6 +221,14 @@ export default function Post() {
}
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);
if (currentCommentPage !== totalPages) {
setCurrentCommentPage(totalPages);
@@ -232,7 +240,7 @@ export default function Post() {
return {
...prev,
items: [...prev.items, newComment],
total: prev.totalCount + 1
totalCount: prev.totalCount + 1
};
} else {
// 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 => {
if (!prev) return null;
const newItems = prev.items.filter(c => c.id !== commentId);
const newTotalCount = prev.totalCount - 1;
if (newItems.length === 0 && 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 };
});
};