aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-article.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils/hooks/use-article.ts')
-rw-r--r--src/utils/hooks/use-article.ts37
1 files changed, 37 insertions, 0 deletions
diff --git a/src/utils/hooks/use-article.ts b/src/utils/hooks/use-article.ts
new file mode 100644
index 0000000..5cf0e51
--- /dev/null
+++ b/src/utils/hooks/use-article.ts
@@ -0,0 +1,37 @@
+import useSWR from 'swr';
+import {
+ articleBySlugQuery,
+ fetchAPI,
+ getArticleFromRawData,
+} from '../../services/graphql';
+import type { Article, RawArticle } from '../../types';
+
+export type UseArticleConfig = {
+ /**
+ * A fallback article
+ */
+ fallback?: Article;
+ /**
+ * The article slug
+ */
+ slug?: string;
+};
+
+/**
+ * Retrieve an article by slug.
+ *
+ * @param {UseArticleConfig} config - The config.
+ * @returns {Article|undefined} The matching article if it exists.
+ */
+export const useArticle = ({
+ slug,
+ fallback,
+}: UseArticleConfig): Article | undefined => {
+ const { data } = useSWR(
+ slug ? { query: articleBySlugQuery, variables: { slug } } : null,
+ fetchAPI<RawArticle, typeof articleBySlugQuery>,
+ {}
+ );
+
+ return data ? getArticleFromRawData(data.post) : fallback;
+};