From a3eb518dcccaebd0f48c708c189ad2fcb07f0f73 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Sun, 21 Aug 2022 13:50:18 +0200
Subject: fix(comments): load all comments on a post

Previously, only the first 10 comments was loaded. So I update the
fetching method to retrieve all the comments on a post.
Also, I choose to order comments on client side because of a bug
with WPGraphQL.
Finally, I renamed the Comment type to SingleComment to avoid conflict
with existing types.
---
 src/utils/hooks/use-comments.tsx | 27 +++++++--------------------
 1 file changed, 7 insertions(+), 20 deletions(-)

(limited to 'src/utils/hooks/use-comments.tsx')

diff --git a/src/utils/hooks/use-comments.tsx b/src/utils/hooks/use-comments.tsx
index cb0848b..a695bd7 100644
--- a/src/utils/hooks/use-comments.tsx
+++ b/src/utils/hooks/use-comments.tsx
@@ -1,38 +1,25 @@
-import { fetchAPI } from '@services/graphql/api';
-import {
-  buildCommentsTree,
-  getCommentFromRawData,
-} from '@services/graphql/comments';
-import { commentsQuery } from '@services/graphql/comments.query';
-import { Comment } from '@ts/types/app';
-import { RawComment } from '@ts/types/raw-data';
+import { getAllComments } from '@services/graphql/comments';
+import { SingleComment } from '@ts/types/app';
 import useSWR from 'swr';
 
 export type UseCommentsConfig = {
   contentId?: string | number;
-  fallback?: Comment[];
+  fallback?: SingleComment[];
 };
 
 /**
  * Retrieve the comments of a page/article.
  *
  * @param {string | number} contentId - A page/article id.
- * @returns {Comment[]|undefined}
+ * @returns {SingleComment[]|undefined}
  */
 const useComments = ({
   contentId,
   fallback,
-}: UseCommentsConfig): Comment[] | undefined => {
-  const { data } = useSWR(
-    contentId ? { query: commentsQuery, variables: { contentId } } : null,
-    fetchAPI<RawComment, typeof commentsQuery>
-  );
+}: UseCommentsConfig): SingleComment[] | undefined => {
+  const { data } = useSWR(contentId ? { contentId } : null, getAllComments);
 
-  const comments = data?.comments.nodes.map((comment) =>
-    getCommentFromRawData(comment)
-  );
-
-  return comments ? buildCommentsTree(comments) : fallback;
+  return data || fallback;
 };
 
 export default useComments;
-- 
cgit v1.2.3

