aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-thematics-list/use-thematics-list.ts
blob: f63815a3fdca8e2700866299adb15f9ecc11b94c (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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import useSWR from 'swr';
import {
  type FetchThematicsListInput,
  fetchThematicsList,
} from '../../../services/graphql';
import type {
  GraphQLConnection,
  Maybe,
  WPThematicPreview,
} from '../../../types';

export type UseThematicsListReturn<
  T extends Maybe<GraphQLConnection<WPThematicPreview>>,
> = {
  isError: boolean;
  isLoading: boolean;
  isValidating: boolean;
  thematics: T extends undefined
    ? Maybe<GraphQLConnection<WPThematicPreview>>
    : GraphQLConnection<WPThematicPreview>;
};

export type UseThematicsListConfig<
  T extends Maybe<GraphQLConnection<WPThematicPreview>>,
> = {
  input?: FetchThematicsListInput;
  fallback?: T;
};

export const useThematicsList = <
  T extends Maybe<GraphQLConnection<WPThematicPreview>>,
>(
  config?: UseThematicsListConfig<T>
): UseThematicsListReturn<T> => {
  const { fallback, input } = config ?? {};
  const { data, error, isLoading, isValidating } = useSWR(
    input ?? {},
    fetchThematicsList,
    { fallbackData: fallback }
  );

  if (error) console.error(error);

  return {
    isError: !!error,
    isLoading,
    isValidating,
    thematics: data,
  } as UseThematicsListReturn<T>;
};