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

useInfiniteQuery.md

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