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

usePrefetchQuery.tsx

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