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 { UsePrefetchQueryOptions } from './types'
5β
6/**
7 * `usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before
8 * a suspense boundary that wraps a component that uses `useSuspenseQuery`. You can pass everything to
9 * `usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always required, and
10 * `queryFn` is required unless a default query function has been defined.
11 *
12 * The prefetch is skipped if the query already has any cached state β including a `pending`/`error` state left
13 * over from a previous attempt β so calling this on every render is cheap and won't refetch data that's
14 * already there or already in flight.
15 * @param options - The {@link UsePrefetchQueryOptions} to use β everything you can pass to `queryClient.query`.
16 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
17 * be used.
18 * @example
19 * ```tsx
20 * import { Suspense } from 'react'
21 * import { usePrefetchQuery } from '@tanstack/react-query'
22 *
23 * function App() {
24 * // Fire the prefetch during render, before the suspense boundary below.
25 * usePrefetchQuery({
26 * queryKey: ['posts'],
27 * queryFn: fetchPosts,
28 * })
29 *
30 * return (
31 * <Suspense fallback={<h1>Loading posts...</h1>}>
32 * <Posts />
33 * </Suspense>
34 * )
35 * }
36 * ```
37 */
38export function usePrefetchQuery<
39 TQueryFnData = unknown,
40 TError = DefaultError,
41 TData = TQueryFnData,
42 TQueryData = TQueryFnData,
43 TQueryKey extends QueryKey = QueryKey,
44>(
45 options: UsePrefetchQueryOptions<
46 TQueryFnData,
47 TError,
48 TData,
49 TQueryData,
50 TQueryKey
51 >,
52 queryClient?: QueryClient,
53): void {
54 const client = useQueryClient(queryClient)
55β
56 if (!client.getQueryState(options.queryKey)) {
57 void client.query(options).catch(noop)
58 }
59}