Skip to content

Commit 33f1983

Browse files
committed
feat: cache WakaTime stats and use async fetch
Store fetched stats in sessionStorage with a 5 minute TTL. Switch fetchStats to async/await, set syncing state at start/end, and show a network error toast on fetch failures.
1 parent c24103b commit 33f1983

1 file changed

Lines changed: 32 additions & 13 deletions

File tree

app/components/dashboard/Stats.tsx

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -59,19 +59,38 @@ export default function Stats({
5959
best_day: { date: "", total_seconds: 0 },
6060
});
6161

62-
const fetchStats = () => {
63-
fetch("/api/wakatime/sync")
64-
.then((res) => res.json())
65-
.then((data) => {
66-
if (data.success) {
67-
setStats(data.data);
68-
} else {
69-
toast.error(
70-
data.error || "Failed to fetch stats. Please try syncing again.",
71-
);
72-
}
73-
setSyncing(false);
74-
});
62+
const fetchStats = async () => {
63+
setSyncing(true);
64+
65+
const cached = sessionStorage.getItem("wakatimeStats");
66+
const cacheTime = Number(sessionStorage.getItem("wakatimeStatsTime"));
67+
const now = Date.now();
68+
69+
if (cached && cacheTime && now - cacheTime < 1000 * 60 * 5) {
70+
setStats(JSON.parse(cached));
71+
setSyncing(false);
72+
return;
73+
}
74+
75+
try {
76+
const res = await fetch("/api/wakatime/sync");
77+
const data = await res.json();
78+
79+
if (data.success) {
80+
setStats(data.data);
81+
82+
sessionStorage.setItem("wakatimeStats", JSON.stringify(data.data));
83+
sessionStorage.setItem("wakatimeStatsTime", now.toString());
84+
} else {
85+
toast.error(
86+
data.error || "Failed to fetch stats. Please try syncing again.",
87+
);
88+
}
89+
} catch (err) {
90+
toast.error("Network error. Please try again.");
91+
}
92+
93+
setSyncing(false);
7594
};
7695

7796
useEffect(() => {

0 commit comments

Comments
 (0)