2026-06-16 14:38:51 +02:00
|
|
|
import { useQuery, type QueryKey } from "@tanstack/react-query";
|
|
|
|
|
|
|
|
|
|
// Reusable "live" polling query: a thin wrapper over react-query that refetches on an
|
|
|
|
|
// interval and — by leaving refetchIntervalInBackground at its default false — pauses while
|
|
|
|
|
// the tab is unfocused, so it doesn't poll a server nobody's watching. This is the shared
|
|
|
|
|
// live-progress mechanism: the Scheduler dashboard uses it now; the notification bell and the
|
|
|
|
|
// future yt-dlp job queue reuse it rather than each re-implementing polling.
|
|
|
|
|
export function useLiveQuery<T>(
|
|
|
|
|
key: QueryKey,
|
|
|
|
|
queryFn: () => Promise<T>,
|
2026-06-19 02:43:46 +02:00
|
|
|
// intervalMs may be a function of the latest data, so the poll cadence can adapt to it
|
|
|
|
|
// (e.g. poll faster while a job is running). react-query re-evaluates it after each fetch
|
|
|
|
|
// against fresh data — the right place for this, vs. a React state toggle that can lag or
|
|
|
|
|
// stall the live updates.
|
|
|
|
|
opts: { intervalMs?: number | ((data: T | undefined) => number); enabled?: boolean } = {}
|
2026-06-16 14:38:51 +02:00
|
|
|
) {
|
|
|
|
|
const { intervalMs = 4000, enabled = true } = opts;
|
|
|
|
|
return useQuery({
|
|
|
|
|
queryKey: key,
|
|
|
|
|
queryFn,
|
|
|
|
|
enabled,
|
2026-06-19 02:43:46 +02:00
|
|
|
refetchInterval: !enabled
|
|
|
|
|
? false
|
|
|
|
|
: typeof intervalMs === "function"
|
|
|
|
|
? (query) => intervalMs(query.state.data as T | undefined)
|
|
|
|
|
: intervalMs,
|
2026-06-16 14:38:51 +02:00
|
|
|
refetchIntervalInBackground: false,
|
|
|
|
|
staleTime: 0,
|
|
|
|
|
});
|
|
|
|
|
}
|