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