Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useInfiniteQuery.md

350 lines17.0 KB

1---
2id: useInfiniteQuery
3title: useInfiniteQuery
4redirect_from:
5 - framework/solid/reference/useInfiniteQuery
6---
7​
8## Overview
9​
10```ts
11function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: Accessor<QueryClient>): DefinedUseInfiniteQueryResult<TData, TError>;
12function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: Accessor<QueryClient>): UseInfiniteQueryResult<TData, TError>;
13```
14​
15- [`DefinedInitialDataInfiniteOptions` β†’ `DefinedUseInfiniteQueryResult`](#call-signature-1): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
16- [`UndefinedInitialDataInfiniteOptions` β†’ `UseInfiniteQueryResult`](#call-signature-2): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
17​
18See also: [Parameters](#parameters-summary) Β· [Returns](#returns-summary)
19​
20<a id="call-signature-1"></a>
21​
22## Call Signature
23​
24```ts
25function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: Accessor<QueryClient>): DefinedUseInfiniteQueryResult<TData, TError>;
26```
27​
28Defined in: [packages/solid-query/src/useInfiniteQuery.ts:68](https://github.com/TanStack/query/blob/main/packages/solid-query/src/useInfiniteQuery.ts#L68)
29​
30The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
31`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
32​
33This overload is selected when `initialData` is set.
34​
35### Type Parameters
36​
37#### TQueryFnData
38​
39`TQueryFnData`
40​
41#### TError
42​
43`TError` = `Error`
44​
45#### TData
46​
47`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
48​
49#### TQueryKey
50​
51`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
52​
53#### TPageParam
54​
55`TPageParam` = `unknown`
56​
57### Parameters
58​
59#### options
60​
61[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
62​
63An accessor returning the [DefinedInitialDataInfiniteOptions](../type-aliases/DefinedInitialDataInfiniteOptions.md) to use β€” everything you
64can pass to `useInfiniteQuery`, with `initialData` set.
65​
66#### queryClient?
67​
68`Accessor`\<[`QueryClient`](../classes/QueryClient.md)\>
69​
70An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
71will be used.
72​
73### Returns
74​
75[`DefinedUseInfiniteQueryResult`](../type-aliases/DefinedUseInfiniteQueryResult.md)\<`TData`, `TError`\>
76​
77The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
78`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
79`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
80`InfiniteData<TQueryFnData>` shape.
81​
82### Remarks
83​
84Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
85refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
86actions, or add conditions like `hasNextPage && !isFetching`.
87​
88### See
89​
90[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
91​
92### Example
93​
94```tsx
95import { For } from 'solid-js'
96import { useInfiniteQuery } from '@tanstack/solid-query'
97​
98function Projects() {
99 // `projectsQuery.data` is never `undefined`, thanks to `initialData` β€” even if a refetch fails, so the
100 // list stays visible alongside the error.
101 const projectsQuery = useInfiniteQuery(() => ({
102 queryKey: ['projects'],
103 queryFn: ({ pageParam }) => fetchProjects(pageParam),
104 initialPageParam: 0,
105 getNextPageParam: (lastPage) => lastPage.nextId,
106 initialData: { pages: [], pageParams: [] },
107 }))
108​
109 return (
110 <div>
111 {projectsQuery.isError ? <span>Error: {projectsQuery.error.message}</span> : null}
112 <ul>
113 <For each={projectsQuery.data.pages}>
114 {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
115 </For>
116 </ul>
117 </div>
118 )
120```
121​
122<a id="call-signature-2"></a>
123​
124## Call Signature
125​
126```ts
127function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: Accessor<QueryClient>): UseInfiniteQueryResult<TData, TError>;
128```
129​
130Defined in: [packages/solid-query/src/useInfiniteQuery.ts:184](https://github.com/TanStack/query/blob/main/packages/solid-query/src/useInfiniteQuery.ts#L184)
131​
132The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
133`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
134​
135### Type Parameters
136​
137#### TQueryFnData
138​
139`TQueryFnData`
140​
141#### TError
142​
143`TError` = `Error`
144​
145#### TData
146​
147`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
148​
149#### TQueryKey
150​
151`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
152​
153#### TPageParam
154​
155`TPageParam` = `unknown`
156​
157### Parameters
158​
159#### options
160​
161[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
162​
163An accessor returning the [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use β€” everything
164you can pass to `useInfiniteQuery`.
165​
166#### queryClient?
167​
168`Accessor`\<[`QueryClient`](../classes/QueryClient.md)\>
169​
170An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
171will be used.
172​
173### Returns
174​
175[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\>
176​
177The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
178`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
179`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
180`InfiniteData<TQueryFnData>` shape.
181​
182### Remarks
183​
184Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
185refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
186actions, or add conditions like `hasNextPage && !isFetching`.
187​
188### See
189​
190[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
191​
192### Examples
193​
194Fetching the next page from a "Load More" button click:
195```tsx
196import { For, Match, Switch } from 'solid-js'
197import { useInfiniteQuery } from '@tanstack/solid-query'
198​
199function Projects() {
200 const projectsQuery = useInfiniteQuery(() => ({
201 queryKey: ['projects'],
202 queryFn: ({ pageParam }) => fetchProjects(pageParam),
203 initialPageParam: 0,
204 getNextPageParam: (lastPage) => lastPage.nextId,
205 }))
206​
207 return (
208 <Switch>
209 <Match when={projectsQuery.isPending}>Loading...</Match>
210 <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
211 <Match when={projectsQuery.isSuccess}>
212 <ul>
213 <For each={projectsQuery.data.pages}>
214 {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
215 </For>
216 </ul>
217 <button
218 onClick={() => projectsQuery.fetchNextPage()}
219 disabled={!projectsQuery.hasNextPage || projectsQuery.isFetching}
220 >
221 {projectsQuery.isFetchingNextPage
222 ? 'Loading more...'
223 : projectsQuery.hasNextPage
224 ? 'Load More'
225 : 'Nothing more to load'}
226 </button>
227 </Match>
228 </Switch>
229 )
231```
232​
233Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
234sentinel element after the list:
235```tsx
236import { For, Match, Switch, createEffect, onCleanup } from 'solid-js'
237import { useInfiniteQuery } from '@tanstack/solid-query'
238​
239function Projects() {
240 const projectsQuery = useInfiniteQuery(() => ({
241 queryKey: ['projects'],
242 queryFn: ({ pageParam }) => fetchProjects(pageParam),
243 initialPageParam: 0,
244 getNextPageParam: (lastPage) => lastPage.nextId,
245 }))
246​
247 let sentinelRef: HTMLDivElement | undefined
248​
249 createEffect(() => {
250 if (sentinelRef == null || !projectsQuery.hasNextPage || projectsQuery.isFetching) return
251​
252 const observer = new IntersectionObserver(([entry]) => {
253 if (entry?.isIntersecting) projectsQuery.fetchNextPage()
254 })
255 observer.observe(sentinelRef)
256​
257 onCleanup(() => observer.disconnect())
258 })
259​
260 return (
261 <Switch>
262 <Match when={projectsQuery.isPending}>Loading...</Match>
263 <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
264 <Match when={projectsQuery.isSuccess}>
265 <ul>
266 <For each={projectsQuery.data.pages}>
267 {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
268 </For>
269 </ul>
270 <div ref={sentinelRef}>{projectsQuery.isFetchingNextPage ? 'Loading more...' : null}</div>
271 </Match>
272 </Switch>
273 )
275```
276​
277<a id="parameters-summary"></a>
278​
279## Parameters
280​
281### options
282​
283[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
284​
285An accessor returning the [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use β€” everything
286you can pass to `useInfiniteQuery`.
287​
288<a id="options-properties"></a>
289​
290#### `options` properties
291​
292Built from [`InfiniteQueryOptions`](../interfaces/InfiniteQueryOptions.md#properties). See the type above for what it changes.
293​
294### queryClient?
295​
296`Accessor`\<[`QueryClient`](../classes/QueryClient.md)\>
297​
298An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
299will be used.
300​
301<a id="returns-summary"></a>
302​
303## Returns
304​
305[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\>
306​
307The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
308`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
309`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
310`InfiniteData<TQueryFnData>` shape.
311​
312<a id="result-properties"></a>
313​
314### Result properties
315​
316| Property | Type | Description |
317| ------ | ------ | ------ |
318| <a id="result-property-data"></a> `data` | `TData` \| `undefined` | The last successfully resolved data for the query. |
319| <a id="result-property-dataupdatedat"></a> `dataUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"success"`. |
320| <a id="result-property-error"></a> `error` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. |
321| <a id="result-property-errorupdatecount"></a> `errorUpdateCount` | `number` | The sum of all errors. |
322| <a id="result-property-errorupdatedat"></a> `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. |
323| <a id="result-property-failurecount"></a> `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. |
324| <a id="result-property-failurereason"></a> `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. |
325| <a id="result-property-fetchnextpage"></a> `fetchNextPage` | (`options?`: [`FetchNextPageOptions`](../interfaces/FetchNextPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the next "page" of results. |
326| <a id="result-property-fetchpreviouspage"></a> `fetchPreviousPage` | (`options?`: [`FetchPreviousPageOptions`](../interfaces/FetchPreviousPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the previous "page" of results. |
327| <a id="result-property-fetchstatus"></a> `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. |
328| <a id="result-property-hasnextpage"></a> `hasNextPage` | `boolean` | Will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). |
329| <a id="result-property-haspreviouspage"></a> `hasPreviousPage` | `boolean` | Will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). |
330| <a id="result-property-isenabled"></a> `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. |
331| <a id="result-property-iserror"></a> `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. |
332| <a id="result-property-isfetched"></a> `isFetched` | `boolean` | Will be `true` if the query has been fetched. |
333| <a id="result-property-isfetchedaftermount"></a> `isFetchedAfterMount` | `boolean` | Will be `true` if the query has been fetched after the component mounted. - This property can be used to not show any previously cached data. |
334| <a id="result-property-isfetching"></a> `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. |
335| <a id="result-property-isfetchingnextpage"></a> `isFetchingNextPage` | `boolean` | Will be `true` while fetching the next page with `fetchNextPage`. |
336| <a id="result-property-isfetchingpreviouspage"></a> `isFetchingPreviousPage` | `boolean` | Will be `true` while fetching the previous page with `fetchPreviousPage`. |
337| <a id="result-property-isfetchnextpageerror"></a> `isFetchNextPageError` | `boolean` | Will be `true` if the query failed while fetching the next page. |
338| <a id="result-property-isfetchpreviouspageerror"></a> `isFetchPreviousPageError` | `boolean` | Will be `true` if the query failed while fetching the previous page. |
339| <a id="result-property-isinitialloading"></a> ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. |
340| <a id="result-property-isloading"></a> `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. |
341| <a id="result-property-isloadingerror"></a> `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. |
342| <a id="result-property-ispaused"></a> `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. |
343| <a id="result-property-ispending"></a> `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. |
344| <a id="result-property-isplaceholderdata"></a> `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. |
345| <a id="result-property-isrefetcherror"></a> `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. |
346| <a id="result-property-isrefetching"></a> `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. |
347| <a id="result-property-isstale"></a> `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. |
348| <a id="result-property-issuccess"></a> `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. |
349| <a id="result-property-refetch"></a> `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. |
350| <a id="result-property-status"></a> `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - Will be: - `pending` if there's no cached data and no query attempt was finished yet. - `error` if the query attempt resulted in an error. - `success` if the query has received a response with no errors and is ready to display its data. |