import { createDataClient, DataProvider, isClientError, isTransientError, useDataClient,} from "@/components/ui/server-data"import { holdOver, holds, isPaused, knowsHolds, mapItems, patchSource, pausedRead, queryKind, refreshKey, runPatch, settleQueries, updateItems,} from "@/components/ui/server-data-cache"import { holdSource } from "@/components/ui/server-data-hold"import { networkModeOf, readOptionsOf } from "@/components/ui/server-data-options"import { intervalOf, isPollFetch, requestPoll } from "@/components/ui/server-data-poll"import { holdSource, pageKey, patchSource, readOptionsOf, useInvalidateSource, useHoldSource, usePatchSource, usePageController, useServerInfinite, useServerPage, useServerTotal, useSourceMutation,} from "@/components/ui/use-server-data"import { useServerPoll } from "@/components/ui/use-server-poll"import { defineResource, resourceMeta, useServerQuery, useServerResource } from "@/components/ui/use-server-query"import { useDelayedFlag, useReachEnd } from "@/components/ui/use-server-table"
Reach for the hooks when you build your own screen on a PageSource; the server table, list and combobox already use them.
useServerPage(source, request) loads one page with the query key [...source.key, "page", filter, sort, position, size]: the previous rows stay while the next page loads (previous), a superseded request is aborted through its signal, and it returns items, status (pending, error, success), fetching, total, navigation, error and retry. When the source has fetchTotal, useServerTotal counts beside it, a query of its own that never holds the rows back. useServerInfinite(source, { filter, sort, size }) adds page after page (loadMore, hasMore, loadingMore) by page number or cursor. useServerQuery(key, fetch, { enabled, staleTime, placeholder, keepPrevious, select, seeds }), from use-server-query, loads one resource that isn't paged (a detail, a snapshot, a short list) and returns data, status, fetching, previous, error and retry; fetch({ signal }) is aborted when the key changes or nothing reads it, and a key under the source's ([...tasks.key, "detail", id]) lets the hooks below reach it. select picks what data holds (TanStack's select: memoised, structurally shared, typed as its result). defineResource({ key, fetch, staleTime, seeds }) declares a resource once for every screen that reads it, through useServerResource(resource, params, options); seeds: (data) => [other.seed(params, value)] writes other resources from an answer, mounted or not, unless the fetch was aborted or that resource got data after the fetch started. error is unknown, or the defaultError registered with TanStack's Register, or the type parameter after the data type; the page, infinite, total and mutation hooks take it too. useInvalidateSource(source, { throwOnError }) refreshes everything under the source's key and resolves once the shown queries reloaded; with throwOnError (on the hook or per call) a failed reload rejects, for a toast. useSourceMutation({ mutationFn, source, optimistic }) refreshes it once the change settles, and optimistic: (items, variables) => items shows the change at once and restores the rows if it fails. To write the server's answer instead of refreshing, settleItems: (items, result, variables) => items maps the rows of every page and infinite query under the key (totals stay) and settle: (result, variables, current, queryKey) => data writes every useServerQuery under it (undefined leaves one alone): they reach every cached query under the key, mounted or not, each written query's read in flight is cancelled first, nothing is requested, and the rest of the key is marked stale (a read of it already in flight starts again). A failed mutation refreshes the key unless refreshOnError: false. Every reload these hooks make (useInvalidateSource, a mutation's refresh after success or failure, the restart after settle) starts any read in flight under the key again, its first load included, since it may answer with the data from before the write: the old request's signal aborts, the query stays pending or fetching without an error, and its late answer or AbortError is dropped (TanStack's invalidateQueries joins a first load instead). usePatchSource(source) returns patch({ items, resource }, { refetch, throwOnError }) for a change the app learned of elsewhere (a push event, another request's answer): items(rows) maps every page and infinite query under the key (totals stay) and resource(current, queryKey) every other query (undefined leaves one alone), mounted or not, without a request; a read in flight whose query it writes, and any first read (no data to patch yet), is cancelled silently and started again in the same batch, with or without refetch, so its answer from before the change never lands and nothing stays pending; refetch: true also reloads the key and resolves once the shown queries reloaded; inFlight: "cancel" stops a written query's read instead, and awaitRestarted waits for the restarted reads. The call resolves with { written, cancelled, restarted, refetched }, the query keys it wrote, whose read it stopped, whose read it started again, and that its reload read, so a screen can tell whether a read ran. patchSource(client, source, changes, options) does the same outside React. useHoldSource(source) returns a function that begins a hold, holdSource(client, source) outside React: it cancels every read in flight under the key now and pauses the hooks' reads under it (they show as fetching and send nothing) until hold.patch(changes, options) writes the caller's own answer and ends it, a written query's paused read dropped, or hold.release() ends it without writing, and the paused reads run; the hook releases its holds on unmount. refetchOnWindowFocus, refetchOnReconnect and refetchOnMount (true when stale, "always", false) set when a query reloads on its own: defaults on createDataClient (no reload on focus; stale queries on mount, and on reconnect unless networkMode is always), per hook on useServerQuery, defineResource, useServerResource (the call wins over the definition), useServerPage, useServerInfinite and useServerTotal. Never reload a resource whose reads overwrite per-item ETags a later write sends back: turn focus and reconnect off on its defineResource, since any reader that asks reloads it for all. scope: { id } runs mutations with the same id one at a time in call order, across hooks, each after the one before has settled (its refresh included); a failure doesn't stop the queue, so to stop at the first one set a flag in onError that mutationFn checks. mutationKey finds them with useMutationState. usePageController(source, options) keeps a createPageController for the component's life and follows the URL while mounted. The hooks use the app's QueryClient when one is provided; otherwise a shared default, so nothing has to be mounted. DataProvider provides one with createDataClient defaults when the app has none: two retries except on a 4xx (read from the error's status), 30 s fresh, no refetch on window focus. createDataClient({ retry, retryDelay }) takes a number of retries (the 4xx rule stays), false (none) or a rule (failures, error) => boolean, and isTransientError(error) (a network TypeError, 408, 425, 429 or 5xx) writes the usual one: retry: (failures, error) => failures < 3 && isTransientError(error); mutations never retry. networkMode (online, always, offlineFirst) on createDataClient sets queries and mutations, and every hook (useServerQuery, defineResource, useServerResource, useServerPage, useServerInfinite, useServerTotal, useSourceMutation) takes its own: TanStack's default, online, pauses reads after the browser's offline event, so a page never reaches its error state; use always for a local backend (Electron IPC, localhost) or an app with its own offline UI. Results reach React through TanStack's notifyManager, one setTimeout(0) after a query settles, so a test that awaits a single act() can see the state before it: call notifyManager.setScheduler(queueMicrotask) in the test setup, or wait with findBy/waitFor. With server rendering, mount a DataProvider per request. refetchInterval polls useServerQuery, useServerResource, useServerPage (with its total) and useServerInfinite (every loaded page): a number of ms, false, or a function of the hook's state, (state) => (state.data?.status === "pending" ? 2000 : false), that stops it once the condition ends. The next poll counts from when the last read settled, so requests never stack, and any other read pushes it back; it stops while the document is hidden (TanStack's focusManager) and, visible again, reloads at once when an interval went by, unless refetchIntervalInBackground. A poll keeps the data: fetching and polling are true and status stays success. Hooks that read the same key share one timer at the shortest interval; it stops on unmount and on a key change, and with polling off no timer is set. ServerDataTable and ServerList take refetchInterval (a number) and refetchIntervalInBackground, and neither mark the rows busy nor announce a poll; leave polling out of your own status the same way. useDelayedFlag(active, episode) turns true once a load has taken 400 ms, for a status that says "Loading…" only when it matters, and useReachEnd(onReach, enabled) is a ref that runs onReach when an element scrolls into view, for infinite lists.