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

useInfiniteQuery.ts

389 lines14.2 KB

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