strapi-plugin-comments icon indicating copy to clipboard operation
strapi-plugin-comments copied to clipboard

Nextjs Strapi App , fetching unwanted deleted comments in NextJs frontend.

Open aamitn opened this issue 8 months ago • 0 comments

So we have a NextJs15 + Strapi 5 App and we're using the Strapi 5 Comments Plugin.

  • I can Successfully delete a comment with a DELETE request at http://localhost:1337/api/comments/api::post.post:iruuwrvc6n4sf7wxg729y1uo/comment/42?authorId=Amit%20Kumar%[email protected]

  • This changes the status of the comment in Strapi back-end from "open" to "removed by author"

  • Then when we do a GET request at http://localhost:1337/api/comments/api::post.post:iruuwrvc6n4sf7wxg729y1uo , the comment with id "42" does not show in repose as expected.

  • But when we refresh our NextJS page in front-end, then the status of all deleted comments reverts back to "open" and the above GET request also starts showing the comment with id "42" in response , which is unexpected, this only happens when we refresh the page where our comment component is being used

Comment Fetching Component Code :

const baseUrl = process.env.NEXT_PUBLIC_STRAPI_BASE_URL || "http://localhost:1337";

async function getComments(documentId: string, collectionName = "post", contentType = "post") {
  try {
    const response = await fetch(
      `${baseUrl}/api/comments/api::${collectionName}.${contentType}:${documentId}`,
      { cache: "no-store" } // Prevent stale data
    );

    if (!response.ok) throw new Error("Failed to fetch comments");

    const data = await response.json();
    return data.filter((comment: any) => !comment.removed); // Remove deleted comments
  } catch (error) {
    console.error("Error fetching comments:", error);
    return [];
  }
}

export default async function CommentSection({ documentId, collectionName, contentType }: { documentId: string; collectionName?: string; contentType?: string }) {
  const comments = await getComments(documentId, collectionName, contentType);

  return (
    <div className="p-4 border rounded-md">
      <h3 className="text-lg font-semibold">{comments.length} Comments</h3>
      {comments.length > 0 ? (
        comments.map((comment: any) => (
          <div key={comment.id} className="p-2 border-b">
            <p className="font-semibold">{comment.author.name}</p>
            <p>{comment.content}</p>
          </div>
        ))
      ) : (
        <p className="text-gray-500">No comments yet.</p>
      )}
    </div>
  );
}

Component Usage:

      <CommentSection 
        documentId={post.documentId} 
        collectionName="post" 
        contentType="post"
      />

aamitn avatar Apr 02 '25 11:04 aamitn