summaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-comments.tsx
blob: f430f19c770ed4b5dc7d096b7ec803b428750848 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { fetchAPI, getAPIUrl } 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 useSWR from 'swr';

/**
 * Retrieve the comments of a page/article.
 *
 * @param {string | number} contentId - A page/article id.
 * @returns {Comment[]|undefined}
 */
const useComments = (
  contentId: string | number,
  fallback?: Comment[]
): Comment[] | undefined => {
  const { data } = useSWR(
    { api: getAPIUrl(), query: commentsQuery, variables: { contentId } },
    fetchAPI<RawComment, typeof commentsQuery>
  );

  const comments = data?.comments.nodes.map((comment) =>
    getCommentFromRawData(comment)
  );

  return comments ? buildCommentsTree(comments) : fallback;
};

export default useComments;