Cookies
This website uses cookies to improve the user experience, more information on the legal information path.
Notes
0
years
0
mons
0
days
0
hour
0
mins
0
secs
Sat16Mar8:23 PM
This is the background image
1

Counter for github stars repository

Wed, Jan 11, 2023

This is a simple counter for github stars repository. You can use it in your website or blog.

How to use it? Just fetch the api and you will get the number of stars.

1. Create a github token

Please use the environment variable to store the token.

github.ts

const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });

2. Write the GET method

github.ts

const REPOSITORY = {
owner: 'xabierlameiro',
repo: 'the-last-dance',
};
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const {
data: { stargazers_count },
} = await octokit.rest.repos.get(REPOSITORY);
res.status(200).json(stargazers_count);
} catch (err: Error) {
res.status(500).json({ statusCode: 500, message: err.message });
}
}

3. Use it in your component

Not is necessary to use the useEffect hook for fetch information. You can use the getStaticProps or getServerSideProps hooks. In my case, I use this hook because the blog is a static site and the endpoint is not available in the build time.

StarCounter.tsx

const StarCounter = () => {
const [stars, setStars] = React.useState(0);
React.useEffect(() => {
(async () => {
try {
const stars = await fetch('/api/github').then((res) => res.json());
setStars(stars);
} catch (e) {
setStars(-1);
}
})();
}, []);
if (stars === -2)
return (
<Container>
<AiFillStar className={styles.starred} title="Starred" />
</Container>
);
if (stars === -1)
return (
<Container>
<RxCross2 className={styles.error} title="Error endpoint" />
</Container>
);
if (stars === 0)
return (
<Container>
<FaSpinner className={styles.spinner} title="Loading stars" />
</Container>
);
return (
<Container>
<span>{stars}</span>
</Container>
);
};
export default StarCounter;

Right now you only have to look up to see the result, the counter is highlighted with a yellow star.

Please if you think this content has helped you or you like it, please give me your star. 🤩