Spaces:
Running
Running
Download web/src/lib/use-api.ts from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 2.05 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/web/src/lib/use-api.ts
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/web/src/lib/use-api.ts
-
curl -L -o use-api.ts https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/web/src/lib/use-api.ts
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 }; | |
| } | |