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

useInfiniteQuery.md

438 lines15.6 KB

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