summaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-article.tsx
diff options
context:
space:
mode:
authorArmand Philippot <git@armandphilippot.com>2022-07-22 19:00:50 +0200
committerArmand Philippot <git@armandphilippot.com>2022-07-22 19:00:50 +0200
commitde9a9eac060974a7878f2bb5577f2b135596a555 (patch)
treec443e69acabc7afca7b37b8d5d5156088da3a785 /src/utils/hooks/use-article.tsx
parentfe3922d039bdb5d4c063bc73543abc53a57d8464 (diff)
refactor(article): wrap useSWR with a custom hook to revalidate article
Diffstat (limited to 'src/utils/hooks/use-article.tsx')
-rw-r--r--src/utils/hooks/use-article.tsx24
1 files changed, 24 insertions, 0 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;