@@ -13,20 +13,73 @@ const spin = keyframes({
1313 } ,
1414} )
1515
16+ const CACHE_KEY = 'github_star_count'
17+ const CACHE_DURATION = 60 * 60 * 1000 // 1 hour in milliseconds
18+
19+ interface CachedData {
20+ count : number
21+ timestamp : number
22+ }
23+
1624export default function StarButton ( ) {
1725 const [ starCount , setStarCount ] = useState < number | null > ( null )
1826
1927 useEffect ( ( ) => {
2028 const abortController = new AbortController ( )
29+
30+ const getCachedData = ( ) : CachedData | null => {
31+ try {
32+ const cached = localStorage . getItem ( CACHE_KEY )
33+ if ( ! cached ) return null
34+
35+ const data : CachedData = JSON . parse ( cached )
36+ const now = Date . now ( )
37+
38+ // Check if cache is still valid
39+ if ( now - data . timestamp < CACHE_DURATION ) {
40+ return data
41+ }
42+
43+ // Cache expired, remove it
44+ localStorage . removeItem ( CACHE_KEY )
45+ return null
46+ } catch {
47+ return null
48+ }
49+ }
50+
51+ const setCachedData = ( count : number ) => {
52+ try {
53+ const data : CachedData = {
54+ count,
55+ timestamp : Date . now ( ) ,
56+ }
57+ localStorage . setItem ( CACHE_KEY , JSON . stringify ( data ) )
58+ } catch {
59+ // Ignore localStorage errors
60+ }
61+ }
62+
2163 const fetchStarCount = async ( ) => {
64+ // Try to get from cache first
65+ const cached = getCachedData ( )
66+ if ( cached ) {
67+ setStarCount ( cached . count )
68+ return
69+ }
70+
71+ // If no cache, fetch from API
2272 try {
2373 const data = await fetch (
2474 'https://api.github.com/repos/dev-five-git/devup-ui' ,
2575 {
2676 signal : abortController . signal ,
2777 } ,
2878 ) . then ( ( res ) => res . json ( ) )
29- setStarCount ( data . stargazers_count )
79+
80+ const count = data . stargazers_count
81+ setStarCount ( count )
82+ setCachedData ( count )
3083 } catch ( error ) {
3184 if ( error !== 'unmounted' ) console . error ( error )
3285 } finally {
0 commit comments