aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-comments.ts
blob: 94a2d7e7fca44d6260f6162fbb24d046ebd9779b (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
import useSWR from 'swr';
import {
  type FetchCommentsListInput,
  fetchCommentsList,
  convertWPCommentToComment,
  buildCommentsTree,
} from '../../services/graphql';
import type { SingleComment } from '../../types';

export type UseCommentsConfig = FetchCommentsListInput & {
  fallback?: SingleComment[];
};

/**
 * Retrieve the comments of a page/article.
 *
 * @param {string | number} contentId - A page/article id.
 * @returns {SingleComment[]|undefined}
 */
export const useComments = ({
  fallback,
  ...input
}: UseCommentsConfig): SingleComment[] | undefined => {
  const { data } = useSWR(input, fetchCommentsList, {});

  if (!data) return fallback;

  const comments = data.map(convertWPCommentToComment);
  const commentsTree = buildCommentsTree(comments);

  return commentsTree;
};