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

useInfiniteQuery.md

436 lines14.9 KB

1---
2id: useInfiniteQuery
3title: useInfiniteQuery
4redirect_from:
5 - framework/vue/reference/useInfiniteQuery
6---
7​
8## Overview
9​
10```ts
11function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: MaybeRefOrGetter<DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>>, queryClient?: QueryClient): UseInfiniteQueryReturnType<TData, TError>;
12function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: MaybeRefOrGetter<UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>>, queryClient?: QueryClient): UseInfiniteQueryReturnType<TData, TError>;
13function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: MaybeRefOrGetter<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>>, queryClient?: QueryClient): UseInfiniteQueryReturnType<TData, TError>;
14```
15​
16- [`MaybeRefOrGetter` β†’ `UseInfiniteQueryReturnType`](#call-signature-1): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
17- [`MaybeRefOrGetter` β†’ `UseInfiniteQueryReturnType`](#call-signature-2): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
18- [`MaybeRefOrGetter` β†’ `UseInfiniteQueryReturnType`](#call-signature-3): Fallback overload for options whose `initialData` presence isn't statically known β€” for example, a `ref`/reactive object built up conditionally, rather than a plain object literal. Prefer one of the other overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
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, TData, TQueryKey, TPageParam>(options: MaybeRefOrGetter<DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>>, queryClient?: QueryClient): UseInfiniteQueryReturnType<TData, TError>;
28```
29​
30Defined in: [packages/vue-query/src/useInfiniteQuery.ts:127](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useInfiniteQuery.ts#L127)
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, so the resulting `data` is never `undefined` (unless
36a `select` changes `TData` to include `undefined`).
37​
38`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
39(`() => ...`). `queryKey` reacts through a `ref` for the array itself, or `ref`s and reactive getters as
40individual entries β€” the array itself can't be a bare getter.
41​
42### Type Parameters
43​
44#### TQueryFnData
45​
46`TQueryFnData`
47​
48#### TError
49​
50`TError` = `Error`
51​
52#### TData
53​
54`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
55​
56#### TQueryKey
57​
58`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
59​
60#### TPageParam
61​
62`TPageParam` = `unknown`
63​
64### Parameters
65​
66#### options
67​
68`MaybeRefOrGetter`\<[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>
69​
70The [DefinedInitialDataInfiniteOptions](../type-aliases/DefinedInitialDataInfiniteOptions.md) to use β€” everything you can pass to
71`useInfiniteQuery`, with `initialData` set.
72​
73#### queryClient?
74​
75[`QueryClient`](../classes/QueryClient.md)
76​
77Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
78will be used.
79​
80### Returns
81​
82[`UseInfiniteQueryReturnType`](../type-aliases/UseInfiniteQueryReturnType.md)\<`TData`, `TError`\>
83​
84The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
85`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.value.pages` and
86`data.value.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
87`InfiniteData<TQueryFnData>` shape.
88​
89### Remarks
90​
91Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
92refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
93actions, or add conditions like `hasNextPage && !isFetching`.
94​
95### Example
96​
97```vue
98<script setup lang="ts">
99import { useInfiniteQuery } from '@tanstack/vue-query'
100​
101// `data` is never `undefined`, thanks to `initialData` β€” even if a refetch fails, so the
102// list stays visible alongside the error.
103const { data, isError, error } = useInfiniteQuery({
104 queryKey: ['projects'],
105 queryFn: ({ pageParam }) => fetchProjects(pageParam),
106 initialPageParam: 0,
107 getNextPageParam: (lastPage) => lastPage.nextId,
108 initialData: { pages: [], pageParams: [] },
109})
110</script>
111​
112<template>
113 <span v-if="isError">Error: {{ error.message }}</span>
114 <ul>
115 <template v-for="page in data.pages" :key="page.nextId">
116 <li v-for="project in page.projects" :key="project.id">{{ project.name }}</li>
117 </template>
118 </ul>
119</template>
120```
121​
122<a id="call-signature-2"></a>
123​
124## Call Signature
125​
126```ts
127function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: MaybeRefOrGetter<UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>>, queryClient?: QueryClient): UseInfiniteQueryReturnType<TData, TError>;
128```
129​
130Defined in: [packages/vue-query/src/useInfiniteQuery.ts:258](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useInfiniteQuery.ts#L258)
131​
132The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
133`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
134​
135`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
136(`() => ...`). `queryKey` reacts through a `ref` for the array itself, or `ref`s and reactive getters as
137individual entries β€” the array itself can't be a bare getter.
138​
139### Type Parameters
140​
141#### TQueryFnData
142​
143`TQueryFnData`
144​
145#### TError
146​
147`TError` = `Error`
148​
149#### TData
150​
151`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
152​
153#### TQueryKey
154​
155`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
156​
157#### TPageParam
158​
159`TPageParam` = `unknown`
160​
161### Parameters
162​
163#### options
164​
165`MaybeRefOrGetter`\<[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>
166​
167The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use β€” everything you can pass to
168`useInfiniteQuery`.
169​
170#### queryClient?
171​
172[`QueryClient`](../classes/QueryClient.md)
173​
174Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
175will be used.
176​
177### Returns
178​
179[`UseInfiniteQueryReturnType`](../type-aliases/UseInfiniteQueryReturnType.md)\<`TData`, `TError`\>
180​
181The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
182`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.value.pages` and
183`data.value.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
184`InfiniteData<TQueryFnData>` shape.
185​
186### Remarks
187​
188Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
189refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
190actions, or add conditions like `hasNextPage && !isFetching`.
191​
192### Examples
193​
194Fetching the next page from a "Load More" button click:
195```vue
196<script setup lang="ts">
197import { useInfiniteQuery } from '@tanstack/vue-query'
198​
199const {
200 data,
201 isPending,
202 isError,
203 error,
204 fetchNextPage,
205 hasNextPage,
206 isFetching,
207 isFetchingNextPage,
208} = useInfiniteQuery({
209 queryKey: ['projects'],
210 queryFn: ({ pageParam }) => fetchProjects(pageParam),
211 initialPageParam: 0,
212 getNextPageParam: (lastPage) => lastPage.nextId,
213})
214</script>
215​
216<template>
217 <span v-if="isPending">Loading...</span>
218 <span v-else-if="isError">Error: {{ error.message }}</span>
219 <template v-else>
220 <ul>
221 <template v-for="page in data.pages" :key="page.nextId">
222 <li v-for="project in page.projects" :key="project.id">{{ project.name }}</li>
223 </template>
224 </ul>
225 <button @click="fetchNextPage()" :disabled="!hasNextPage || isFetching">
226 {{ isFetchingNextPage ? 'Loading more...' : hasNextPage ? 'Load More' : 'Nothing more to load' }}
227 </button>
228 </template>
229</template>
230```
231​
232Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
233sentinel element after the list:
234```vue
235<script setup lang="ts">
236import { onUnmounted, ref, watch } from 'vue'
237import { useInfiniteQuery } from '@tanstack/vue-query'
238​
239const {
240 data,
241 isPending,
242 isError,
243 error,
244 fetchNextPage,
245 hasNextPage,
246 isFetching,
247 isFetchingNextPage,
248} = useInfiniteQuery({
249 queryKey: ['projects'],
250 queryFn: ({ pageParam }) => fetchProjects(pageParam),
251 initialPageParam: 0,
252 getNextPageParam: (lastPage) => lastPage.nextId,
253})
254​
255const sentinel = ref<HTMLElement>()
256let observer: IntersectionObserver | undefined
257​
258watch(sentinel, (el) => {
259 observer?.disconnect()
260 if (el == null) return
261​
262 observer = new IntersectionObserver(([entry]) => {
263 if (entry?.isIntersecting && hasNextPage.value && !isFetching.value) {
264 fetchNextPage()
265 }
266 })
267 observer.observe(el)
268})
269​
270onUnmounted(() => observer?.disconnect())
271</script>
272​
273<template>
274 <span v-if="isPending">Loading...</span>
275 <span v-else-if="isError">Error: {{ error.message }}</span>
276 <template v-else>
277 <ul>
278 <template v-for="page in data.pages" :key="page.nextId">
279 <li v-for="project in page.projects" :key="project.id">{{ project.name }}</li>
280 </template>
281 </ul>
282 <div ref="sentinel">{{ isFetchingNextPage ? 'Loading more...' : '' }}</div>
283 </template>
284</template>
285```
286​
287<a id="call-signature-3"></a>
288​
289## Call Signature
290​
291```ts
292function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: MaybeRefOrGetter<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>>, queryClient?: QueryClient): UseInfiniteQueryReturnType<TData, TError>;
293```
294​
295Defined in: [packages/vue-query/src/useInfiniteQuery.ts:351](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useInfiniteQuery.ts#L351)
296​
297Fallback overload for options whose `initialData` presence isn't statically known β€” for example, a
298`ref`/reactive object built up conditionally, rather than a plain object literal. Prefer one of the other
299overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
300​
301`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
302(`() => ...`). `queryKey` reacts through a `ref` for the array itself, or `ref`s and reactive getters as
303individual entries β€” the array itself can't be a bare getter.
304​
305### Type Parameters
306​
307#### TQueryFnData
308​
309`TQueryFnData`
310​
311#### TError
312​
313`TError` = `Error`
314​
315#### TData
316​
317`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
318​
319#### TQueryKey
320​
321`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
322​
323#### TPageParam
324​
325`TPageParam` = `unknown`
326​
327### Parameters
328​
329#### options
330​
331`MaybeRefOrGetter`\<[`UseInfiniteQueryOptions`](../type-aliases/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>
332​
333A `ref`, plain value, or reactive getter resolving to the [UseInfiniteQueryOptions](../type-aliases/UseInfiniteQueryOptions.md) to
334use.
335​
336#### queryClient?
337​
338[`QueryClient`](../classes/QueryClient.md)
339​
340Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
341will be used.
342​
343### Returns
344​
345[`UseInfiniteQueryReturnType`](../type-aliases/UseInfiniteQueryReturnType.md)\<`TData`, `TError`\>
346​
347The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
348`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`.
349​
350### Examples
351​
352Passing a whole-options getter so `maxPages` reacts to a setting stored elsewhere, not just `queryKey`:
353```vue
354<script setup lang="ts">
355import { useInfiniteQuery } from '@tanstack/vue-query'
356​
357const props = defineProps<{ projectId: number; maxPages: number }>()
358​
359const { data } = useInfiniteQuery(() => ({
360 queryKey: ['project', props.projectId, 'issues'],
361 queryFn: ({ pageParam }) => fetchIssues(props.projectId, pageParam),
362 initialPageParam: 0,
363 getNextPageParam: (lastPage) => lastPage.nextId,
364 maxPages: props.maxPages,
365}))
366</script>
367​
368<template>
369 <template v-for="page in data?.pages" :key="page.nextId">
370 <li v-for="issue in page.issues" :key="issue.id">{{ issue.title }}</li>
371 </template>
372</template>
373```
374​
375A query that's disabled, type-safe, until `postId` is set β€” pass `skipToken` as `queryFn` instead of
376setting `enabled: false`. This requires a whole-options getter: `queryFn` isn't itself reactive, so the
377getter is what re-evaluates it on every change to `props.postId`:
378```vue
379<script setup lang="ts">
380import { skipToken, useInfiniteQuery } from '@tanstack/vue-query'
381​
382const props = defineProps<{ postId: string | undefined }>()
383​
384// Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled.
385const { data, isLoading, isError, error } = useInfiniteQuery(() => {
386 const postId = props.postId
387 return {
388 queryKey: ['post', postId, 'comments'],
389 queryFn:
390 postId != null
391 ? ({ pageParam }) => fetchComments(postId, pageParam)
392 : skipToken,
393 initialPageParam: 0,
394 getNextPageParam: (lastPage) => lastPage.nextId,
395 }
396})
397</script>
398​
399<template>
400 <span v-if="props.postId == null">Select a post</span>
401 <span v-else-if="isLoading">Loading...</span>
402 <span v-else-if="isError">Error: {{ error.message }}</span>
403 <ul v-else>
404 <template v-for="page in data.pages" :key="page.nextId">
405 <li v-for="comment in page.comments" :key="comment.id">{{ comment.text }}</li>
406 </template>
407 </ul>
408</template>
409```
410​
411<a id="parameters-summary"></a>
412​
413## Parameters
414​
415### options
416​
417`MaybeRefOrGetter`\<[`UseInfiniteQueryOptions`](../type-aliases/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>
418​
419A `ref`, plain value, or reactive getter resolving to the [UseInfiniteQueryOptions](../type-aliases/UseInfiniteQueryOptions.md) to
420use.
421​
422### queryClient?
423​
424[`QueryClient`](../classes/QueryClient.md)
425​
426Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
427will be used.
428​
429<a id="returns-summary"></a>
430​
431## Returns
432​
433[`UseInfiniteQueryReturnType`](../type-aliases/UseInfiniteQueryReturnType.md)\<`TData`, `TError`\>
434​
435The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
436`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`.