Open History to see the last commit
1import { noop } from '@tanstack/query-core'
2import { useQueryClient } from './QueryClientProvider'
3import type {
4 DefaultError,
5 InfiniteData,
6 QueryClient,
7 QueryKey,
8} from '@tanstack/query-core'
9import type { UsePrefetchInfiniteQueryOptions } from './types'
10β
11/**
12 * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render,
13 * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass
14 * everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though
15 * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required unless
16 * a default query function has been defined.
17 *
18 * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages,
19 * as well as pageParam information, and should return a single variable that will be passed to your query
20 * function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available.
21 *
22 * The prefetch is skipped if the query already has any cached state β including a `pending`/`error` state left
23 * over from a previous attempt β so calling this on every render is cheap and won't refetch data that's
24 * already there or already in flight.
25 * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use β everything you can pass to `queryClient.infiniteQuery`.
26 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
27 * be used.
28 * @example
29 * ```tsx
30 * import { Suspense } from 'react'
31 * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/react-query'
32 *
33 * const projectsOptions = infiniteQueryOptions({
34 * queryKey: ['projects'],
35 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
36 * initialPageParam: 0,
37 * getNextPageParam: (lastPage) => lastPage.nextId,
38 * })
39 *
40 * function App() {
41 * // Fire the prefetch during render, before the suspense boundary below.
42 * usePrefetchInfiniteQuery(projectsOptions)
43 *
44 * return (
45 * <Suspense fallback={<h1>Loading projects...</h1>}>
46 * <Projects />
47 * </Suspense>
48 * )
49 * }
50 * ```
51 */
52export function usePrefetchInfiniteQuery<
53 TQueryFnData = unknown,
54 TError = DefaultError,
55 TData = InfiniteData<TQueryFnData>,
56 TQueryKey extends QueryKey = QueryKey,
57 TPageParam = unknown,
58>(
59 options: UsePrefetchInfiniteQueryOptions<
60 TQueryFnData,
61 TError,
62 TData,
63 TQueryKey,
64 TPageParam
65 >,
66 queryClient?: QueryClient,
67): void {
68 const client = useQueryClient(queryClient)
69β
70 if (!client.getQueryState(options.queryKey)) {
71 void client.infiniteQuery(options).catch(noop)
72 }
73}