Infinite queries
client.infiniteQuery is for lists that load page by page: "load more" buttons, endless scroll, cursors. It wraps TanStack's useInfiniteQuery and takes care of the one thing that is specific to an endpoint: turning a page param into a request.
Declare one
The endpoint must have a querySchema, because the page param is a set of query parameters. getNextPageParam returns the query parameters for the next page, or undefined when there is none.
With an existing endpoint, the pagination settings are the second argument: client.infiniteQuery(listPosts, { getNextPageParam }).
Use it
data is TanStack's InfiniteData: pages holds each validated response and pageParams the param that produced it. The hook result and its options are TanStack's; see Infinite Queries for maxPages, select and the rest.
How a page is requested
Each page calls the endpoint with the page param merged over the params you passed to the hook:
So getNextPageParam only returns what changes. Filters and page size stay in the hook's params and are part of the cache key; the page param is not.
The first page param is the hook's params, exactly as you passed them. They are not run through querySchema first, so a schema default does not show up in lastPageParam. Set initialPageParam when the first page needs something else.
Page numbers
getNextPageParam receives four arguments: the last page, all pages, the last page param and all page params. For numbered pages, count from the last param:
For lists that load in both directions, add getPreviousPageParam with the same shape and use fetchPreviousPage from the hook result.
Helpers and cache entries
An infinite query has every member a query has: use, useSuspense, the options call, key, fetch, prefetch, ensure, getData, setData and invalidate. The differences:
- The cached value is
InfiniteData, sosetDataupdaters receive{ pages, pageParams }. fetch,prefetchandensureload the first page.withResponse: truewraps every page as{ data, response }.
Infinite entries are stored apart from plain ones. You can declare client.query and client.infiniteQuery on the same endpoint and neither overwrites the other; the key of the infinite form carries an 'infinite' marker.
Related: Keys and invalidation.