TanStack Query with safe defaults, opt-in IndexedDB persistence, polled first pages, and a sign-out clear that waits for the cache to finish restoring.
The client never retries a query or a mutation, so an error shows at once and a failed write never repeats, and doesn’t refetch when the window regains focus. Unused data stays in memory for maxAgeSeconds, 10 days by default, as long as it stays persisted.
Persistence is opt-in: only a query with meta: { persist: true } is saved, once it succeeds, so private or short-lived data never reaches the disk. Mutations are never saved, since one replayed after a reload could act twice. Change buster when a release changes a persisted query’s data, so older copies are thrown away.
Where IndexedDB is missing, such as in some private windows, the provider provides the client without persistence, and the persister does nothing.
clearQueryCache waits for the client’s restoration from its persisted copy, so restored data can’t come back after the clear. It then clears the memory and removes the persisted copy, and concurrent calls share one clear.
Paging after a first page
When one query loads a whole screen, including the first page of a list, useSeededInfiniteQuery pages through the rest of the list without fetching that first page again:
Each firstPageUpdatedAt and first page form a generation. When the screen’s query refetches, the list starts over from its new first page, any page in flight is aborted, and a late page of an older generation is dropped. Initial publication waits with no data. Refreshing an already loaded key shows only the fresh first page while publication finishes, so the list stays visible; isReady and continuation controls remain false until publication completes. Changing the key, withdrawing the first page or evicting the cache hides retained data. Components using the same key share one generation, so one unmounting aborts nothing. fetchNextPage and refetch, which retries only the page that failed, keep their identity. The query never fetches by itself and is never persisted; gcTimeSeconds, 0 by default, keeps its pages after the last component unmounts. Something that forces it to fetch before the first page arrives rejects with FIRST_PAGE_NOT_READY.
Query state
The query-state helpers read the flags of any query, or of useSeededInfiniteQuery’s result: isQueryLoading, isQueryReadyForInitialDisplay, which holds back stale cached data until it’s refetched after mount, canQueryLoadMore, isQueryLoadingMore, and isQueryResultDataAvailable, for a list of queries.
Query boundaries
useQueryBoundary decides what a screen shows around the queries its content needs, and leaves the drawing to the app:
ts
import { useQueryBoundary } from 'jg-tanstack-query';const boundary = useQueryBoundary({ queries: [project, members], resolutionKey: projectId, // a new key hides the content until its queries resolve isAccessDenied: (error) => getErrorCode(error) === 'ACCESS_DENIED',});// { canRenderContent, isLoaderVisible, hasError, errorPresentation, failedQueries,// loadMoreQuery, retryFailed }
The content waits until every query has data for the key that’s fresh, or fetched since mount, so cached data from an earlier visit never shows as current. Once it shows, refetches, pagination, and background errors keep it on screen, with errorPresentation: 'retained'; an error before then, or one that leaves a query without data, is blocking. A new key, or an error isAccessDenied recognizes, hides the content in the same render, and after an access loss it returns only once every query settles with current data, even when isInitialResolutionApproved says the app approved the key’s data before. loadMoreQuery is the first query when it pages and the content shows, and retryFailed refetches every failed query; it and the result keep their identity while nothing changes. RECIPES.md has an unstyled boundary component.
Data bound to the signed-in user
useIdentityBoundQueryApproval decides whether an app may show the data of a query bound to the signed-in user, such as the current account, so a change of user never shows the previous one’s data:
ts
import { useIdentityBoundQueryApproval } from 'jg-tanstack-query';const { shouldPublishQueryData, isIdentityApproved, hasConfirmedIdentityMismatch } = useIdentityBoundQueryApproval({ authenticatedIdentityKey: session?.key ?? null, // changes with each sign-in authenticatedSubjectId: session?.accountId, approvedSubjectId: storedAccount?.id, // the data the app already shows querySubjectId: accountQuery.data?.id, isQueryReady: accountQuery.isSuccess, isQueryError: accountQuery.isError, });
Store the query’s data only while shouldPublishQueryData, when it belongs to the signed-in subject. isIdentityApproved turns true once the stored data matches the signed-in identity, stays true through refetches and failed fetches, resets for a new identity, even of the same subject, until its own data matches, and clears on sign-out. hasConfirmedIdentityMismatch means a settled query returned another subject’s data, so sign out or reset. The result keeps its identity while its decisions don’t change.
Polling
createPollingQueryOptions makes a query refetch on an interval while it’s useful, built on TanStack Query’s own focus and online managers:
ts
import { useQuery } from '@tanstack/react-query';import { createPollingQueryOptions } from 'jg-tanstack-query';const exportJob = useQuery({ queryKey: ['exports', exportId], queryFn: () => fetchExport(exportId), ...createPollingQueryOptions<IExport>({ intervalSeconds: (data) => (data.status === 'running' ? 2 : false), // or a number of seconds isEnabled: isPanelOpen, // optional }),});
It polls only while isEnabled holds and the last fetch succeeded: a hidden tab pauses it, the tab or the network coming back fetches once, and a failed fetch stops it until something else refetches the query. The interval can follow the data, and false stops it, such as once a job finished. An interval that isn’t positive and finite throws INVALID_POLLING_INTERVAL.
A paged list that stays fresh
usePolledFirstPage keeps a cursor-paged list current without reading every loaded page again: it reads only the first page each interval and merges it into the pages the list holds:
mergeFirstPage, which the hook uses, matches rows by ID: rows the list doesn’t hold yet go ahead of its first page, rows it holds take the new version wherever they are, and the pages after the first keep their place, cursors and page params, so a list that loaded more keeps them and its scroll. The poll pauses and stops as createPollingQueryOptions does, starts from the page the list read, so opening the list reads its first page once, and is dropped as soon as the list unmounts. Pages hold their rows in data.
Errors
Code
When
FIRST_PAGE_NOT_READY
A seeded infinite query was forced to fetch before its first page arrived
INVALID_POLLING_INTERVAL
A polling interval isn’t positive, finite seconds
Generated from TSDoc
API reference
Every export of [email protected], 36 in all, with its signature, its errors, and an example.
Clears a client's cached data, in memory and persisted, such as at sign-out, so the next person on the device sees none of it. It first waits for the client's restoration from its persisted copy, so restored data can't come back after the clear. Concurrent calls share one clear.
Creates a persister that keeps a TanStack Query client's dehydrated copy in IndexedDB, through idb-keyval. It opens the database on first use, not when it's created, and does nothing where IndexedDB is missing.
Builds the options of a query that polls while it's useful: every intervalSeconds while it's enabled and its last fetch succeeded, on TanStack Query's own focus and online managers, so it pauses in a hidden tab, fetches once when the tab or the network comes back, and stops after a failed fetch, until something else refetches it. The interval can follow the data, such as stopping once a job finished. Spread the result into useQuery's options.
Creates a TanStack Query client with safe defaults: queries and mutations never retry, a focused window doesn't refetch, and unused data stays in memory as long as it stays persisted. Create it once, outside any component.
Checks whether a query's data can be shown when a screen first renders: it didn't fail, and its data is fresh, or was fetched since the component mounted. Stale data from the cache waits for the refetch, so a screen never shows data from a previous visit as current.
Merges a newly read first page into a paged list's loaded pages, matching rows by ID: rows the list doesn't hold yet go ahead of its first page, and rows it holds take the new version where they are, on any page. The pages after the first keep their place, their cursors and their page params, so a list that loaded more never loses them. Merging the same page twice changes nothing more.
Provides a TanStack Query client that restores its persisted copy on start, and persists the queries that opt in with meta: { persist: true }, never mutations. Where IndexedDB is missing, it provides the client without persistence.
Decides whether an app may show the data of a query bound to the signed-in user, such as the current account: it publishes the query's data only when it belongs to the signed-in subject, approves the identity once that data is published and matches what the app already shows, and keeps the approval through refetches and failed fetches, so the app doesn't blank out. A new identity, even for the same subject, waits for its own matching data, and signing out clears the approval. A settled query with another subject's data is a confirmed mismatch. An app whose stored data already matches a returning identity is approved from the first render.
Keeps a paged list fresh by reading only its first page every intervalSeconds, and merging each read into the loaded pages by row ID with mergeFirstPage: new rows go ahead, rows the list holds take the new version, and the pages after the first are never read again, so a list that loaded more keeps them and its scroll. It polls as createPollingQueryOptions does: while the tab is visible, the browser is online and the last read succeeded. The poll starts from the page the list read, so opening the list reads its first page once, and it's dropped as soon as the list unmounts, so it's never kept, persisted or merged late.
Decides what a screen shows around the queries its content needs, without rendering anything, so any design system can draw the loader, the error, and the content.
The content waits until every query has data for the current resolutionKey that's fresh, or fetched since mount, so stale cached data never shows as current. Once it shows, refetches, pagination, and background errors keep it on screen, with errorPresentation: 'retained'. A new key, or an error isAccessDenied recognizes, hides it in the same render; after an access loss, it returns only once every query settles with current data, even with isInitialResolutionApproved.
The queries, the key of what they show, whether the app already approved its data, and how to recognize a lost access.
Returns
IQueryBoundaryState<TQuery>
Whether to render the content or a loader, the error state and the failed queries, the query for a load-more control, and a stable retryFailed. The result keeps its identity while none of it changes.
Pages through a list whose first page another query already fetched, such as one that loads a whole screen, without fetching that page again. The first page is published into an infinite query under queryKey, and continuationQueryFn fetches only the pages after it.
Each firstPageUpdatedAt and first page form a generation. A new generation cancels any page in flight and starts over from the new first page, and an older publication that finishes late never replaces a newer one. Components that use the same key share one generation and its pages, so one unmounting aborts nothing. Initial publication waits with no data. A refresh of an already published key shows its new first page while publication finishes, with continuations disabled. A withdrawn first page, changed key or evicted cache never exposes retained pages. The query never fetches by itself and is never persisted.
type IPollingOptions<TData> = { intervalSeconds: number | ((data: TData) => number | false); isEnabled?: boolean | undefined;};
Members
intervalSecondsproperty
number | ((data: TData) => number | false)
the seconds between fetches, positive and finite, or a function of the latest data that gives them, or false to stop polling, such as once a job finished
isEnabledproperty
boolean
whether to poll at all, such as only while a panel is open. Defaults to true
What useSeededInfiniteQuery returns: a subset of TanStack's infinite query result, shaped so query boundaries and load-more controls read it like any other query. Initial publication waits with no data; a same-key refresh shows only the current first page until publication enables continuations. fetchNextPage and refetch keep their identity across renders.
the signed-in session's identity, such as ${accountId}:${authUserId}, which changes when another user, or the same user through another sign-in, takes over; null when signed out
authenticatedSubjectIdproperty
string | undefined
the subject the session is signed in as, such as the account's id, or undefined before it's known
approvedSubjectIdproperty
string | undefined
the subject the data the app already shows belongs to, such as from its persisted store, or undefined when it shows none
querySubjectIdproperty
string | undefined
the subject the query's latest data belongs to, or undefined without data
isQueryReadyproperty
boolean
whether the query has settled with data for the current identity
what the content shows, such as a project's id: a new key hides the content until the queries resolve for it
isInitialResolutionApprovedproperty
boolean
whether the app already approved this key's data, such as before the boundary remounted, so cached data shows at once. It never brings content back after an access loss
isAccessDeniedproperty
(error: unknown) => boolean
whether a query's error means the user lost access, such as a 403, which hides the content at once, even approved, until every query succeeds again. Defaults to never
the key of the query that holds the pages, which no other query may use
firstPageproperty
TPage | undefined
the first page, which another query, such as one for a whole screen, already fetched
firstPageUpdatedAtproperty
number
when the first page was fetched, such as that query's dataUpdatedAt. A new value, or a new first page, starts a new generation: the pages loaded so far are dropped