aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-article/use-article.ts
blob: d5234cb349fa5517848fa96ad7441c4055d095c9 (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
import useSWR from 'swr';
import { convertPostToArticle, fetchPost } from '../../../services/graphql';
import type { Article, Maybe, WPPost } from '../../../types';

export type UseArticleReturn<T extends Maybe<WPPost>> = {
  article: T extends undefined ? Maybe<Article> : Article;
  isError: boolean;
  isLoading: boolean;
  isValidating: boolean;
};

export const useArticle = <T extends Maybe<WPPost>>(
  slug: string,
  fallback?: T
): UseArticleReturn<T> => {
  const { data, error, isLoading, isValidating } = useSWR(slug, fetchPost, {
    fallbackData: fallback,
  });

  if (error) console.error(error);

  return {
    article: data ? convertPostToArticle(data) : undefined,
    isError: !!error,
    isLoading: isLoading && !data,
    isValidating,
  } as UseArticleReturn<T>;
};