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