Spaces:
Running
Running
| /** | |
| * Dashboard store — fetches and caches dashboard overview data. | |
| */ | |
| import { create } from "zustand"; | |
| import { dashboardApi, DashboardOverview } from "@/lib/api"; | |
| interface DashboardState { | |
| data: DashboardOverview | null; | |
| isLoading: boolean; | |
| error: string | null; | |
| lastFetched: number | null; | |
| fetch: (userId?: string, force?: boolean) => Promise<void>; | |
| reset: () => void; | |
| } | |
| const CACHE_TTL = 2 * 60 * 1000; // 2 minutes | |
| export const useDashboardStore = create<DashboardState>((set, get) => ({ | |
| data: null, | |
| isLoading: false, | |
| error: null, | |
| lastFetched: null, | |
| fetch: async (userId, force = false) => { | |
| const { lastFetched, isLoading } = get(); | |
| if (isLoading) return; | |
| if (!force && lastFetched && Date.now() - lastFetched < CACHE_TTL) return; | |
| set({ isLoading: true, error: null }); | |
| try { | |
| const data = await dashboardApi.overview(userId); | |
| set({ data, isLoading: false, lastFetched: Date.now() }); | |
| } catch (err) { | |
| set({ error: (err as Error).message, isLoading: false }); | |
| } | |
| }, | |
| reset: () => set({ data: null, isLoading: false, error: null, lastFetched: null }), | |
| })); | |