|
| 1 | +'use client' |
| 2 | + |
| 3 | +import './StarButton.css' |
| 4 | + |
1 | 5 | import { Center, css, Flex, Image, Text } from '@devup-ui/react' |
2 | 6 | import Link from 'next/link' |
| 7 | +import { useEffect, useState } from 'react' |
| 8 | + |
| 9 | +export default function StarButton() { |
| 10 | + const [starCount, setStarCount] = useState<number | null>(null) |
3 | 11 |
|
4 | | -export default async function StarButton() { |
5 | | - const res = await fetch('https://api.github.com/repos/dev-five-git/devup-ui') |
6 | | - const data = await res.json() |
7 | | - const starCount = data.stargazers_count |
| 12 | + useEffect(() => { |
| 13 | + const abortController = new AbortController() |
| 14 | + const fetchStarCount = async () => { |
| 15 | + try { |
| 16 | + const data = await fetch( |
| 17 | + 'https://api.github.com/repos/dev-five-git/devup-ui', |
| 18 | + { |
| 19 | + signal: abortController.signal, |
| 20 | + }, |
| 21 | + ).then((res) => res.json()) |
| 22 | + setStarCount(data.stargazers_count) |
| 23 | + } catch (error) { |
| 24 | + console.error(error) |
| 25 | + } finally { |
| 26 | + setStarCount((prev) => (typeof prev === 'number' ? prev : -1)) |
| 27 | + } |
| 28 | + } |
| 29 | + fetchStarCount() |
| 30 | + |
| 31 | + return () => { |
| 32 | + abortController.abort() |
| 33 | + } |
| 34 | + }, []) |
8 | 35 |
|
9 | 36 | return ( |
10 | 37 | <Link |
@@ -58,9 +85,18 @@ export default async function StarButton() { |
58 | 85 | h="100%" |
59 | 86 | px="16px" |
60 | 87 | > |
61 | | - <Text color="$primary" textAlign="center" typography="buttonLsemiB"> |
62 | | - {starCount} |
63 | | - </Text> |
| 88 | + {starCount === null ? ( |
| 89 | + <Image |
| 90 | + alt="Loading" |
| 91 | + animation="spin 1s linear infinite" |
| 92 | + boxSize="20px" |
| 93 | + src="/spinner.svg" |
| 94 | + /> |
| 95 | + ) : ( |
| 96 | + <Text color="$primary" textAlign="center" typography="buttonLsemiB"> |
| 97 | + {starCount} |
| 98 | + </Text> |
| 99 | + )} |
64 | 100 | </Center> |
65 | 101 | </Flex> |
66 | 102 | </Link> |
|
0 commit comments