Open History to see the last commit
1import { noop } from '@tanstack/query-core'
2import { getCurrentScope, unref, watchEffect } from 'vue-demi'
3import { useQueryClient } from './useQueryClient'
4import { cloneDeepUnref } from './utils'
5import type {
6 DefaultError,
7 OmitKeyof,
8 QueryExecuteOptions,
9 QueryKey,
10 SkipToken,
11} from '@tanstack/query-core'
12import type { QueryClient } from './queryClient'
13import type { MaybeRefDeep, MaybeRefOrGetter } from './types'
14β
15/**
16 * The options accepted by `usePrefetchQuery` β everything you can pass to `queryClient.query`, except that
17 * `queryFn` can't be `skipToken`.
18 */
19export type UsePrefetchQueryOptions<
20 TQueryFnData,
21 TError,
22 TData,
23 TQueryData,
24 TQueryKey extends QueryKey,
25> = OmitKeyof<
26 QueryExecuteOptions<
27 TQueryFnData,
28 TError,
29 TData,
30 TQueryData,
31 TQueryKey,
32 never
33 >,
34 'queryFn'
35> & {
36 queryFn?: Exclude<
37 QueryExecuteOptions<
38 TQueryFnData,
39 TError,
40 TData,
41 TQueryData,
42 TQueryKey,
43 never
44 >['queryFn'],
45 SkipToken
46 >
47}
48β
49/**
50 * Checks whether an option was passed as a getter function.
51 * @param value - The option value.
52 * @returns `true` if `value` is a function.
53 */
54function isGetter<T>(value: MaybeRefOrGetter<T>): value is () => T {
55 return typeof value === 'function'
56}
57β
58/**
59 * `usePrefetchQuery` does not return anything β it fires a prefetch as a reactive side effect, useful for
60 * kicking off a fetch ahead of the component that will actually render the data with `useQuery`. You can pass
61 * everything to `usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always
62 * required, and `queryFn` is required unless a default query function has been defined.
63 *
64 * The prefetch is skipped if the query already has any cached state β including a `pending`/`error` state left
65 * over from a previous attempt β so it won't refetch data that's already there or already in flight. It
66 * re-runs whenever a reactive dependency in `options` (built with `queryOptions`, for example) changes.
67 *
68 * Fire this during render, before a suspense boundary that wraps a component using `useQuery`'s `suspense()`
69 * β see the {@link https://tanstack.com/query/latest/docs/framework/vue/guides/suspense | Suspense guide}.
70 * @param options - A `ref`, plain value, or reactive getter resolving to the {@link UsePrefetchQueryOptions} to
71 * use β everything you can pass to `queryClient.query`.
72 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
73 * will be used.
74 * @example
75 * ```vue
76 * <script setup lang="ts">
77 * import { usePrefetchQuery } from '@tanstack/vue-query'
78 * import Posts from './Posts.vue'
79 *
80 * // Fire the prefetch as soon as this component runs, before `Posts` mounts and calls `useQuery`.
81 * usePrefetchQuery({
82 * queryKey: ['posts'],
83 * queryFn: fetchPosts,
84 * })
85 * </script>
86 *
87 * <template>
88 * <Posts />
89 * </template>
90 * ```
91 */
92export function usePrefetchQuery<
93 TQueryFnData = unknown,
94 TError = DefaultError,
95 TData = TQueryFnData,
96 TQueryData = TQueryFnData,
97 TQueryKey extends QueryKey = QueryKey,
98>(
99 options: MaybeRefOrGetter<
100 MaybeRefDeep<
101 UsePrefetchQueryOptions<
102 TQueryFnData,
103 TError,
104 TData,
105 TQueryData,
106 TQueryKey
107 >
108 >
109 >,
110 queryClient?: QueryClient,
111): void {
112 if (process.env.NODE_ENV === 'development') {
113 if (!getCurrentScope()) {
114 console.warn(
115 'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
116 )
117 }
118 }
119β
120 const client = queryClient || useQueryClient()
121β
122 watchEffect(() => {
123 const resolvedOptions = isGetter(options) ? options() : unref(options)
124 const clonedOptions: UsePrefetchQueryOptions<
125 TQueryFnData,
126 TError,
127 TData,
128 TQueryData,
129 TQueryKey
130 > = cloneDeepUnref(resolvedOptions)
131β
132 if (!client.getQueryState(clonedOptions.queryKey)) {
133 void client.query(clonedOptions).catch(noop)
134 }
135 })
136}