Spaces:
Running
Running
File size: 2,050 Bytes
03608f2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | "use client";
import { useCallback, useEffect, useState } from "react";
import { api, ApiError, type RequestOptions } from "@/lib/api";
export interface ApiState<T> {
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<T>(
path: string | null,
opts: { query?: RequestOptions["query"]; pollMs?: number } = {},
): ApiState<T> {
const [data, setData] = useState<T>();
const [error, setError] = useState<ApiError | Error>();
const [settledKey, setSettledKey] = useState<string | null>(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<T>(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<typeof setInterval> | 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 };
}
|