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

useInfiniteQuery.ts

385 lines13.0 KB

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