blob: 6281a54a6c729a9a7797d08bb6129ccf13192c8e (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
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';
export type UseArticleConfig = {
fallback?: Article;
slug?: string;
};
/**
* Retrieve an article by slug.
*
* @param {string} slug - The article slug.
* @param {Article} fallback - A fallback article.
* @returns {Article|undefined} The matching article if it exists.
*/
const useArticle = ({
slug,
fallback,
}: UseArticleConfig): Article | undefined => {
const { data } = useSWR(
slug
? { api: getAPIUrl(), query: articleBySlugQuery, variables: { slug } }
: null,
fetchAPI<RawArticle, typeof articleBySlugQuery>
);
return data ? getArticleFromRawData(data.post) : fallback;
};
export default useArticle;
|