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

useInfiniteQuery.ts

390 lines12.1 KB

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