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

useInfiniteQuery.md

352 lines17.5 KB

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