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