aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-github-api.tsx
blob: aa9e3f7a27c53dd2e67a0dab6555e0ffb49d414a (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, { Fetcher } from 'swr';
import { SWRResult } from '../../types';

export type RepoData = {
  created_at: string;
  updated_at: string;
  stargazers_count: number;
};

const fetcher: Fetcher<RepoData, string> = (...args) =>
  fetch(...args).then((res) => res.json());

/**
 * Retrieve data from Github API.
 *
 * @param repo - The Github repo (`owner/repo-name`).
 * @returns The repository data.
 */
export const useGithubApi = (repo: string): SWRResult<RepoData> => {
  const apiUrl = repo ? `https://api.github.com/repos/${repo}` : null;
  const { data, error } = useSWR<RepoData>(apiUrl, fetcher);

  return {
    data,
    isLoading: !error && !data,
    isError: error,
  };
};