From 958569e09071e4bb290f0ec120b4309ae5983d2d Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Mon, 24 Jan 2022 14:52:04 +0100 Subject: refactor(project): replace repo api call method with hook and swr Instead of using post slug and an environment variable to fetch repo data, I use the given repo in each project MDX file. It allows me to fetch data from another user/organization if needed. To make it work, I no longer provide the full URL in MDX file. The new format is: "User/repo-slug". I also replaced the fetch method with SWR to improve caching and to avoid React complaining about cleanup useEffect. --- src/utils/hooks/useGithubApi.tsx | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/utils/hooks/useGithubApi.tsx (limited to 'src/utils/hooks/useGithubApi.tsx') diff --git a/src/utils/hooks/useGithubApi.tsx b/src/utils/hooks/useGithubApi.tsx new file mode 100644 index 0000000..4b0b3b2 --- /dev/null +++ b/src/utils/hooks/useGithubApi.tsx @@ -0,0 +1,23 @@ +import { RepoData } from '@ts/types/repos'; +import useSWR, { Fetcher } from 'swr'; + +const fetcher: Fetcher = (...args) => + fetch(...args).then((res) => res.json()); + +/** + * Retrieve data from Github API. + * @param repo The repo name. Format: "User/project-slug". + * @returns {object} The data and two booleans to determine if is loading/error. + */ +const useGithubApi = (repo: string) => { + const apiUrl = repo ? `https://api.github.com/repos/${repo}` : null; + const { data, error } = useSWR(apiUrl, fetcher); + + return { + data, + isLoading: !error && !data, + isError: error, + }; +}; + +export default useGithubApi; -- cgit v1.2.3