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