MCPcopy Create free account
hub / github.com/DavidHDev/react-bits / useStars

Function useStars

src/hooks/useStars.js:9–62  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

7const DEFAULT_STARS = 33200;
8
9export const useStars = () => {
10 const [stars, setStars] = useState(DEFAULT_STARS);
11
12 useSingleEffect(() => {
13 const fetchStars = async () => {
14 try {
15 const cachedData = localStorage.getItem(CACHE_KEY);
16
17 if (cachedData) {
18 const { count, timestamp } = JSON.parse(cachedData);
19 const now = Date.now();
20
21 if (now - timestamp < CACHE_DURATION && count && count !== 'NAN') {
22 setStars(count);
23 return;
24 }
25 }
26
27 const count = await getStarsCount();
28
29 // Only update if we got a valid count
30 if (count && count !== 'NAN') {
31 localStorage.setItem(
32 CACHE_KEY,
33 JSON.stringify({
34 count,
35 timestamp: Date.now()
36 })
37 );
38
39 setStars(count);
40 }
41 } catch (error) {
42 console.error('Error fetching stars:', error);
43
44 const cachedData = localStorage.getItem(CACHE_KEY);
45 if (cachedData) {
46 const { count } = JSON.parse(cachedData);
47 if (count && count !== 'NAN') {
48 setStars(count);
49 } else {
50 setStars(DEFAULT_STARS);
51 }
52 } else {
53 setStars(DEFAULT_STARS);
54 }
55 }
56 };
57
58 fetchStars();
59 }, []);
60
61 return stars;
62};

Callers 3

HeaderFunction · 0.90
StarCardFunction · 0.90
NavbarFunction · 0.90

Calls 1

fetchStarsFunction · 0.85

Tested by

no test coverage detected