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

useInfiniteQuery.ts

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