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

useInfiniteQuery.ts

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