"use client"; import { useCallback, useEffect, useState } from "react"; import { api, ApiError, type RequestOptions } from "@/lib/api"; export interface ApiState { data: T | undefined; error: ApiError | Error | undefined; loading: boolean; reload: () => void; } /** GET a path and keep it fresh. ``path=null`` skips the request. ``pollMs`` re-fetches in * the background while the tab is visible. */ export function useApi( path: string | null, opts: { query?: RequestOptions["query"]; pollMs?: number } = {}, ): ApiState { const [data, setData] = useState(); const [error, setError] = useState(); const [settledKey, setSettledKey] = useState(null); const [nonce, setNonce] = useState(0); const key = path === null ? null : `${path}?${JSON.stringify(opts.query ?? {})}`; useEffect(() => { if (path === null || key === null) return; const ctrl = new AbortController(); const run = () => api(path, { query: opts.query, signal: ctrl.signal }) .then((d) => { if (ctrl.signal.aborted) return; setData(d); setError(undefined); }) .catch((e: unknown) => { if (ctrl.signal.aborted) return; setError(e instanceof Error ? e : new Error(String(e))); }) .finally(() => { if (!ctrl.signal.aborted) setSettledKey(key); }); void run(); let timer: ReturnType | undefined; if (opts.pollMs) { timer = setInterval(() => { if (document.visibilityState === "visible") void run(); }, opts.pollMs); } return () => { ctrl.abort(); if (timer) clearInterval(timer); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- key captures path + query }, [key, nonce, opts.pollMs]); const reload = useCallback(() => setNonce((n) => n + 1), []); return { data, error, loading: key !== null && settledKey !== key, reload }; }