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

useInfiniteQuery.ts

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