summaryrefslogtreecommitdiffstats
path: root/src/utils/hooks
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils/hooks')
-rw-r--r--src/utils/hooks/use-article.tsx24
-rw-r--r--src/utils/hooks/use-comments.tsx8
2 files changed, 28 insertions, 4 deletions
diff --git a/src/utils/hooks/use-article.tsx b/src/utils/hooks/use-article.tsx
new file mode 100644
index 0000000..3a173dd
--- /dev/null
+++ b/src/utils/hooks/use-article.tsx
@@ -0,0 +1,24 @@
+import { fetchAPI, getAPIUrl } from '@services/graphql/api';
+import { getArticleFromRawData } from '@services/graphql/articles';
+import { articleBySlugQuery } from '@services/graphql/articles.query';
+import { Article } from '@ts/types/app';
+import { RawArticle } from '@ts/types/raw-data';
+import useSWR from 'swr';
+
+/**
+ * Retrieve an article by slug.
+ *
+ * @param {string} slug - The article slug.
+ * @param {Article} fallback - A fallback article.
+ * @returns {Article} The matching article.
+ */
+const useArticle = (slug: string, fallback: Article): Article => {
+ const { data } = useSWR(
+ { api: getAPIUrl(), query: articleBySlugQuery, variables: { slug } },
+ fetchAPI<RawArticle, typeof articleBySlugQuery>
+ );
+
+ return data ? getArticleFromRawData(data.post) : fallback;
+};
+
+export default useArticle;
diff --git a/src/utils/hooks/use-comments.tsx b/src/utils/hooks/use-comments.tsx
index cc9e560..f430f19 100644
--- a/src/utils/hooks/use-comments.tsx
+++ b/src/utils/hooks/use-comments.tsx
@@ -10,7 +10,8 @@ import useSWR from 'swr';
/**
* Retrieve the comments of a page/article.
- * @param contentId - A page/article id.
+ *
+ * @param {string | number} contentId - A page/article id.
* @returns {Comment[]|undefined}
*/
const useComments = (
@@ -19,15 +20,14 @@ const useComments = (
): Comment[] | undefined => {
const { data } = useSWR(
{ api: getAPIUrl(), query: commentsQuery, variables: { contentId } },
- fetchAPI<RawComment, typeof commentsQuery>,
- { fallback }
+ fetchAPI<RawComment, typeof commentsQuery>
);
const comments = data?.comments.nodes.map((comment) =>
getCommentFromRawData(comment)
);
- return comments ? buildCommentsTree(comments) : undefined;
+ return comments ? buildCommentsTree(comments) : fallback;
};
export default useComments;