From fe3922d039bdb5d4c063bc73543abc53a57d8464 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Fri, 22 Jul 2022 18:32:53 +0200 Subject: fix(comments): refresh comments on changes or new comment --- src/utils/hooks/use-comments.tsx | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/utils/hooks/use-comments.tsx (limited to 'src/utils/hooks') diff --git a/src/utils/hooks/use-comments.tsx b/src/utils/hooks/use-comments.tsx new file mode 100644 index 0000000..cc9e560 --- /dev/null +++ b/src/utils/hooks/use-comments.tsx @@ -0,0 +1,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 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, + { fallback } + ); + + const comments = data?.comments.nodes.map((comment) => + getCommentFromRawData(comment) + ); + + return comments ? buildCommentsTree(comments) : undefined; +}; + +export default useComments; -- cgit v1.2.3