aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-topics-list/use-topics-list.ts
blob: 20f760bbcbd685cfe1b4539512f6e93241ac6d9d (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
import useSWR from 'swr';
import {
  type FetchTopicsListInput,
  fetchTopicsList,
} from '../../../services/graphql';
import type { GraphQLConnection, Maybe, WPTopicPreview } from '../../../types';

export type UseTopicsListReturn<
  T extends Maybe<GraphQLConnection<WPTopicPreview>>,
> = {
  isError: boolean;
  isLoading: boolean;
  isValidating: boolean;
  topics: T extends undefined
    ? Maybe<GraphQLConnection<WPTopicPreview>>
    : GraphQLConnection<WPTopicPreview>;
};

export type UseTopicsListConfig<
  T extends Maybe<GraphQLConnection<WPTopicPreview>>,
> = {
  input?: FetchTopicsListInput;
  fallback?: T;
};

export const useTopicsList = <
  T extends Maybe<GraphQLConnection<WPTopicPreview>>,
>(
  config?: UseTopicsListConfig<T>
): UseTopicsListReturn<T> => {
  const { fallback, input } = config ?? {};
  const { data, error, isLoading, isValidating } = useSWR(
    input ?? {},
    fetchTopicsList,
    { fallbackData: fallback }
  );

  if (error) console.error(error);

  return {
    isError: !!error,
    isLoading: isLoading && !data,
    isValidating,
    topics: data,
  } as UseTopicsListReturn<T>;
};