aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-github-repo-meta/use-github-repo-meta.ts
blob: 3567311bc62e0a6ddf7f3ebe607ae4161e20f535 (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
import useSWR from 'swr';
import {
  type FetchGithubRepoMetaInput,
  fetchGithubRepoMeta,
} from '../../../services/github';
import type { GithubRepositoryMeta, Maybe, Nullable } from '../../../types';

export type UseGithubRepoMetaReturn<
  I extends Nullable<FetchGithubRepoMetaInput>,
  T extends Maybe<GithubRepositoryMeta>,
> = {
  isError: I extends null ? false : boolean;
  isLoading: I extends null ? false : boolean;
  isValidating: I extends null ? false : boolean;
  meta: I extends null
    ? null
    : T extends undefined
      ? Maybe<GithubRepositoryMeta>
      : GithubRepositoryMeta;
};

export const useGithubRepoMeta = <
  I extends Nullable<FetchGithubRepoMetaInput>,
  T extends Maybe<GithubRepositoryMeta>,
>(
  input: I,
  fallback?: T
) => {
  const { data, error, isLoading, isValidating } = useSWR(
    input,
    fetchGithubRepoMeta,
    {
      fallbackData: fallback,
    }
  );

  if (error) console.error(error);

  return {
    isError: !!error,
    isLoading: input !== null && isLoading && !data,
    isValidating,
    meta: data,
  } as UseGithubRepoMetaReturn<I, T>;
};