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

useInfiniteQuery.ts

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