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

useInfiniteQuery.ts

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