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

useInfiniteQuery.ts

416 lines13.4 KB

1import { InfiniteQueryObserver } from '@tanstack/query-core'
2import type {
3 DefaultError,
4 InfiniteData,
5 QueryClient,
6 QueryKey,
7 QueryObserver,
8} from '@tanstack/query-core'
9​
10import type {
11 DefinedInitialDataInfiniteOptions,
12 UndefinedInitialDataInfiniteOptions,
13} from './infiniteQueryOptions'
14import type {
15 DefinedUseInfiniteQueryResult,
16 UseInfiniteQueryOptions,
17 UseInfiniteQueryResult,
18} from './types'
19import { useBaseQuery } from './useBaseQuery'
20​
21/**
22 * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `queryFn`,
23 * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
24 *
25 * This overload is selected when `initialData` is set.
26 *
27 * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
28 * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
29 * actions, or add conditions like `hasNextPage && !isFetching`.
30 * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
31 * @param options - The {@link DefinedInitialDataInfiniteOptions} to use β€” everything you can pass to `useInfiniteQuery`, with `initialData` set.
32 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
33 * be used.
34 * @returns The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`,
35 * `fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and
36 * `isFetchingPreviousPage`.
37 *
38 * @example
39 * ```tsx
40 * import { useInfiniteQuery } from '@tanstack/preact-query'
41 *
42 * function Projects() {
43 * // `data` is never `undefined`, thanks to `initialData` β€” even if a refetch fails, so the
44 * // list stays visible alongside the error.
45 * const { data, isError, error } = useInfiniteQuery({
46 * queryKey: ['projects'],
47 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
48 * initialPageParam: 0,
49 * getNextPageParam: (lastPage) => lastPage.nextId,
50 * initialData: { pages: [], pageParams: [] },
51 * })
52 *
53 * return (
54 * <div>
55 * {isError ? <span>Error: {error.message}</span> : null}
56 * <ul>
57 * {data.pages.map((page) => page.projects.map((p) => <li key={p.id}>{p.name}</li>))}
58 * </ul>
59 * </div>
60 * )
61 * }
62 * ```
63 */
64export function useInfiniteQuery<
65 TQueryFnData,
66 TError = DefaultError,
67 TData = InfiniteData<TQueryFnData>,
68 TQueryKey extends QueryKey = QueryKey,
69 TPageParam = unknown,
70>(
71 options: DefinedInitialDataInfiniteOptions<
72 TQueryFnData,
73 TError,
74 TData,
75 TQueryKey,
76 TPageParam
77 >,
78 queryClient?: QueryClient,
79): DefinedUseInfiniteQueryResult<TData, TError>
80​
81/**
82 * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `queryFn`,
83 * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
84 *
85 * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
86 * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
87 * actions, or add conditions like `hasNextPage && !isFetching`.
88 * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
89 * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use β€” everything you can pass to `useInfiniteQuery`.
90 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
91 * be used.
92 * @returns The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`,
93 * `fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and
94 * `isFetchingPreviousPage`.
95 *
96 * @example
97 * Fetching the next page from a "Load More" button click:
98 * ```tsx
99 * import { useInfiniteQuery } from '@tanstack/preact-query'
100 *
101 * function Projects() {
102 * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
103 * useInfiniteQuery({
104 * queryKey: ['projects'],
105 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
106 * initialPageParam: 0,
107 * getNextPageParam: (lastPage) => lastPage.nextId,
108 * })
109 *
110 * if (isPending) return 'Loading...'
111 * if (isError) return <span>Error: {error.message}</span>
112 *
113 * return (
114 * <>
115 * <ul>
116 * {data.pages.map((page) =>
117 * page.projects.map((project) => <li key={project.id}>{project.name}</li>),
118 * )}
119 * </ul>
120 * <button
121 * onClick={() => fetchNextPage()}
122 * disabled={!hasNextPage || isFetching}
123 * >
124 * {isFetchingNextPage
125 * ? 'Loading more...'
126 * : hasNextPage
127 * ? 'Load More'
128 * : 'Nothing more to load'}
129 * </button>
130 * </>
131 * )
132 * }
133 * ```
134 *
135 * @example
136 * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
137 * sentinel element after the list:
138 * ```tsx
139 * import { useInfiniteQuery } from '@tanstack/preact-query'
140 * import { useEffect, useRef } from 'preact/hooks'
141 *
142 * function Projects() {
143 * const {
144 * data,
145 * isPending,
146 * isError,
147 * error,
148 * fetchNextPage,
149 * hasNextPage,
150 * isFetching,
151 * isFetchingNextPage,
152 * } = useInfiniteQuery({
153 * queryKey: ['projects'],
154 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
155 * initialPageParam: 0,
156 * getNextPageParam: (lastPage) => lastPage.nextId,
157 * })
158 *
159 * const sentinelRef = useRef<HTMLDivElement>(null)
160 *
161 * useEffect(() => {
162 * const sentinel = sentinelRef.current
163 * if (sentinel == null || !hasNextPage || isFetching) return
164 *
165 * const observer = new IntersectionObserver(([entry]) => {
166 * if (entry?.isIntersecting) fetchNextPage()
167 * })
168 * observer.observe(sentinel)
169 *
170 * return () => observer.disconnect()
171 * }, [hasNextPage, isFetching, fetchNextPage])
172 *
173 * if (isPending) return 'Loading...'
174 * if (isError) return <span>Error: {error.message}</span>
175 *
176 * return (
177 * <>
178 * <ul>
179 * {data.pages.map((page) =>
180 * page.projects.map((project) => <li key={project.id}>{project.name}</li>),
181 * )}
182 * </ul>
183 * <div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
184 * </>
185 * )
186 * }
187 * ```
188 */
189export function useInfiniteQuery<
190 TQueryFnData,
191 TError = DefaultError,
192 TData = InfiniteData<TQueryFnData>,
193 TQueryKey extends QueryKey = QueryKey,
194 TPageParam = unknown,
195>(
196 options: UndefinedInitialDataInfiniteOptions<
197 TQueryFnData,
198 TError,
199 TData,
200 TQueryKey,
201 TPageParam
202 >,
203 queryClient?: QueryClient,
204): UseInfiniteQueryResult<TData, TError>
205​
206/**
207 * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `queryFn`,
208 * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
209 *
210 * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
211 * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
212 * actions, or add conditions like `hasNextPage && !isFetching`.
213 * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
214 * @param options - The {@link UseInfiniteQueryOptions} to use β€” everything you can pass to `useInfiniteQuery`.
215 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
216 * be used.
217 * @returns The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`,
218 * `fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and
219 * `isFetchingPreviousPage`.
220 *
221 * @example
222 * Fetching the next page from a "Load More" button click:
223 * ```tsx
224 * import { useInfiniteQuery } from '@tanstack/preact-query'
225 *
226 * function Projects() {
227 * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
228 * useInfiniteQuery({
229 * queryKey: ['projects'],
230 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
231 * initialPageParam: 0,
232 * getNextPageParam: (lastPage) => lastPage.nextId,
233 * })
234 *
235 * if (isPending) return 'Loading...'
236 * if (isError) return <span>Error: {error.message}</span>
237 *
238 * return (
239 * <>
240 * <ul>
241 * {data.pages.map((page) =>
242 * page.projects.map((project) => <li key={project.id}>{project.name}</li>),
243 * )}
244 * </ul>
245 * <button
246 * onClick={() => fetchNextPage()}
247 * disabled={!hasNextPage || isFetching}
248 * >
249 * {isFetchingNextPage
250 * ? 'Loading more...'
251 * : hasNextPage
252 * ? 'Load More'
253 * : 'Nothing more to load'}
254 * </button>
255 * </>
256 * )
257 * }
258 * ```
259 *
260 * @example
261 * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
262 * sentinel element after the list:
263 * ```tsx
264 * import { useInfiniteQuery } from '@tanstack/preact-query'
265 * import { useEffect, useRef } from 'preact/hooks'
266 *
267 * function Projects() {
268 * const {
269 * data,
270 * isPending,
271 * isError,
272 * error,
273 * fetchNextPage,
274 * hasNextPage,
275 * isFetching,
276 * isFetchingNextPage,
277 * } = useInfiniteQuery({
278 * queryKey: ['projects'],
279 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
280 * initialPageParam: 0,
281 * getNextPageParam: (lastPage) => lastPage.nextId,
282 * })
283 *
284 * const sentinelRef = useRef<HTMLDivElement>(null)
285 *
286 * useEffect(() => {
287 * const sentinel = sentinelRef.current
288 * if (sentinel == null || !hasNextPage || isFetching) return
289 *
290 * const observer = new IntersectionObserver(([entry]) => {
291 * if (entry?.isIntersecting) fetchNextPage()
292 * })
293 * observer.observe(sentinel)
294 *
295 * return () => observer.disconnect()
296 * }, [hasNextPage, isFetching, fetchNextPage])
297 *
298 * if (isPending) return 'Loading...'
299 * if (isError) return <span>Error: {error.message}</span>
300 *
301 * return (
302 * <>
303 * <ul>
304 * {data.pages.map((page) =>
305 * page.projects.map((project) => <li key={project.id}>{project.name}</li>),
306 * )}
307 * </ul>
308 * <div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
309 * </>
310 * )
311 * }
312 * ```
313 *
314 * @example
315 * Warming the cache on hover, so `<Comments>` has data as soon as it's clicked. Requires an
316 * {@link infiniteQueryOptions} factory, so the hook and the imperative call share the same cache entry:
317 * ```tsx
318 * import {
319 * infiniteQueryOptions,
320 * noop,
321 * useInfiniteQuery,
322 * useQueryClient,
323 * } from '@tanstack/preact-query'
324 *
325 * const commentsOptions = (postId: string) =>
326 * infiniteQueryOptions({
327 * queryKey: ['post', postId, 'comments'],
328 * queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
329 * initialPageParam: 0,
330 * getNextPageParam: (lastPage) => lastPage.nextId,
331 * })
332 *
333 * function Comments({ postId }: { postId: string }) {
334 * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId))
335 *
336 * if (isPending) return 'Loading...'
337 * if (isError) return <span>Error: {error.message}</span>
338 *
339 * return (
340 * <ul>
341 * {data.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
342 * </ul>
343 * )
344 * }
345 *
346 * function PostLink({ postId, title }: { postId: string; title: string }) {
347 * const queryClient = useQueryClient()
348 *
349 * return (
350 * <a
351 * href={`/posts/${postId}`}
352 * onMouseEnter={() => queryClient.infiniteQuery(commentsOptions(postId)).catch(noop)}
353 * >
354 * {title}
355 * </a>
356 * )
357 * }
358 * ```
359 *
360 * @example
361 * A query that's disabled, type safe, until `postId` is set β€” pass `skipToken` as `queryFn`
362 * instead of setting `enabled: false`:
363 * ```tsx
364 * import { skipToken, useInfiniteQuery } from '@tanstack/preact-query'
365 *
366 * function Comments({ postId }: { postId: string | undefined }) {
367 * // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled.
368 * const { data, isLoading, isError, error } = useInfiniteQuery({
369 * queryKey: ['post', postId, 'comments'],
370 * queryFn:
371 * postId != null
372 * ? ({ pageParam }) => fetchComments(postId, pageParam)
373 * : skipToken,
374 * initialPageParam: 0,
375 * getNextPageParam: (lastPage) => lastPage.nextId,
376 * })
377 *
378 * if (postId == null) return 'Select a post'
379 * if (isLoading) return 'Loading...'
380 * if (isError) return <span>Error: {error.message}</span>
381 *
382 * return (
383 * <ul>
384 * {data?.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
385 * </ul>
386 * )
387 * }
388 * ```
389 */
390export function useInfiniteQuery<
391 TQueryFnData,
392 TError = DefaultError,
393 TData = InfiniteData<TQueryFnData>,
394 TQueryKey extends QueryKey = QueryKey,
395 TPageParam = unknown,
396>(
397 options: UseInfiniteQueryOptions<
398 TQueryFnData,
399 TError,
400 TData,
401 TQueryKey,
402 TPageParam
403 >,
404 queryClient?: QueryClient,
405): UseInfiniteQueryResult<TData, TError>
406​
407export function useInfiniteQuery(
408 options: UseInfiniteQueryOptions,
409 queryClient?: QueryClient,
410) {
411 return useBaseQuery(
412 options,
413 InfiniteQueryObserver as typeof QueryObserver,
414 queryClient,
415 )