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