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

useInfiniteQuery.ts

363 lines12.4 KB

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