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