Spaces:
Running

WorkPilot-AI / web /src /lib /use-api.ts
Aynkhn's picture
Deploy WorkPilot demo (part 3)
03608f2 verified
Raw History Blame Contribute Delete
2.05 kB
"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 };
}