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/components/ProjectSummary/ProjectSummary.tsx | 41 +++++++++++------------- 1 file changed, 19 insertions(+), 22 deletions(-) (limited to 'src/components') diff --git a/src/components/ProjectSummary/ProjectSummary.tsx b/src/components/ProjectSummary/ProjectSummary.tsx index 0d00f06..5a4f9c8 100644 --- a/src/components/ProjectSummary/ProjectSummary.tsx +++ b/src/components/ProjectSummary/ProjectSummary.tsx @@ -1,36 +1,25 @@ import GithubIcon from '@assets/images/social-media/github.svg'; import GitlabIcon from '@assets/images/social-media/gitlab.svg'; import { t } from '@lingui/macro'; -import { getRepoData } from '@services/repos/github'; import { ProjectMeta } from '@ts/types/app'; -import { RepoData } from '@ts/types/github'; import { slugify } from '@utils/helpers/slugify'; +import useGithubApi from '@utils/hooks/useGithubApi'; import Image from 'next/image'; import { useRouter } from 'next/router'; -import { useEffect, useState } from 'react'; import styles from './ProjectSummary.module.scss'; const ProjectSummary = ({ - slug, title, cover, meta, }: { - slug: string; title: string; cover: string; meta: ProjectMeta; }) => { const { license, repos, technologies } = meta; - const [data, setData] = useState(); const { locale } = useRouter(); - const githubUser = process.env.NEXT_PUBLIC_GITHUB_USER; - - useEffect(() => { - getRepoData(slug) - .then((repoData) => setData(repoData)) - .catch((e) => console.error(e)); - }, [slug]); + const { data } = useGithubApi(repos?.github ? repos.github : ''); const getFormattedDate = (date: string) => { const dateOptions: Intl.DateTimeFormatOptions = { @@ -87,7 +76,10 @@ const ProjectSummary = ({
{t`Repositories`}
{repos.github && (
- + Github @@ -95,7 +87,10 @@ const ProjectSummary = ({ )} {repos.gitlab && (
- + Gitlab @@ -103,15 +98,17 @@ const ProjectSummary = ({ )} )} - {data && ( + {data && repos && (
{t`Popularity`}
-
- ⭐  - - {t`${data.stargazers_count} stars on Github`} - -
+ {repos.github && ( +
+ ⭐  + + {t`${data.stargazers_count} stars on Github`} + +
+ )} )} -- cgit v1.2.3