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

usePrefetchQuery.tsx

63 lines2.1 KB

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 *
17 * @param options - The {@link UsePrefetchQueryOptions} to use β€” everything you can pass to `queryClient.query`.
18 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
19 * be used.
20 * @returns `void` β€” nothing is returned.
21 *
22 * @example
23 * ```tsx
24 * import { Suspense } from 'preact/compat'
25 * import { usePrefetchQuery } from '@tanstack/preact-query'
26 *
27 * function App() {
28 * // Fire the prefetch during render, before the suspense boundary below.
29 * usePrefetchQuery({
30 * queryKey: ['posts'],
31 * queryFn: fetchPosts,
32 * })
33 *
34 * return (
35 * <Suspense fallback={<h1>Loading posts...</h1>}>
36 * <Posts />
37 * </Suspense>
38 * )
39 * }
40 * ```
41 */
42export function usePrefetchQuery<
43 TQueryFnData = unknown,
44 TError = DefaultError,
45 TData = TQueryFnData,
46 TQueryData = TQueryFnData,
47 TQueryKey extends QueryKey = QueryKey,
48>(
49 options: UsePrefetchQueryOptions<
50 TQueryFnData,
51 TError,
52 TData,
53 TQueryData,
54 TQueryKey
55 >,
56 queryClient?: QueryClient,
57) {
58 const client = useQueryClient(queryClient)
59​
60 if (!client.getQueryState(options.queryKey)) {
61 void client.query(options).catch(noop)
62 }