diff options
| author | Armand Philippot <git@armandphilippot.com> | 2022-07-22 18:32:53 +0200 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2022-07-22 18:32:53 +0200 |
| commit | fe3922d039bdb5d4c063bc73543abc53a57d8464 (patch) | |
| tree | c845ee49a7f722f25e59222145f491fa3079e108 | |
| parent | d8fc8d272bffb5c59a17ff774c910b47749dc650 (diff) | |
fix(comments): refresh comments on changes or new comment
| -rw-r--r-- | src/pages/article/[slug].tsx | 5 | ||||
| -rw-r--r-- | src/utils/hooks/use-comments.tsx | 33 |
2 files changed, 35 insertions, 3 deletions
diff --git a/src/pages/article/[slug].tsx b/src/pages/article/[slug].tsx index ea679ab..f720fa6 100644 --- a/src/pages/article/[slug].tsx +++ b/src/pages/article/[slug].tsx @@ -26,6 +26,7 @@ import { getWebPageSchema, } from '@utils/helpers/schema-org'; import useBreadcrumb from '@utils/hooks/use-breadcrumb'; +import useComments from '@utils/hooks/use-comments'; import usePrism, { type OptionalPrismPlugin } from '@utils/hooks/use-prism'; import useReadingTime from '@utils/hooks/use-reading-time'; import useSettings from '@utils/hooks/use-settings'; @@ -58,9 +59,7 @@ const ArticlePage: NextPageWithLayout<ArticlePageProps> = ({ const { data: article } = useSWR(() => slug, getArticleBySlug, { fallbackData: post, }); - const { data: commentsData } = useSWR(() => id, getPostComments, { - fallbackData: comments, - }); + const commentsData = useComments(post.id, comments); const { items: breadcrumbItems, schema: breadcrumbSchema } = useBreadcrumb({ title: article?.title || '', url: `/article/${slug}`, 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<RawComment, typeof commentsQuery>, + { fallback } + ); + + const comments = data?.comments.nodes.map((comment) => + getCommentFromRawData(comment) + ); + + return comments ? buildCommentsTree(comments) : undefined; +}; + +export default useComments; |
