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

usePrefetchInfiniteQuery.tsx

74 lines2.7 KB

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