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