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

useInfiniteQuery.ts

434 lines14.3 KB

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