Open History to see the last commit
1import { getCurrentScope, unref, watchEffect } from 'vue-demi'
2import { noop } from '@tanstack/query-core'
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
17 * `queryClient.query`, except that `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 *
52 * @param value - The option value.
53 * @returns `true` if `value` is a function.
54 */
55function isGetter<T>(value: MaybeRefOrGetter<T>): value is () => T {
56 return typeof value === 'function'
57}
58β
59/**
60 * `usePrefetchQuery` does not return anything β it fires a prefetch as a
61 * reactive side effect, useful for kicking off a fetch ahead of the component
62 * that will actually render the data with `useQuery`. You can pass everything
63 * to `usePrefetchQuery` that you can pass to `queryClient.query`, though
64 * `queryKey` is always required, and `queryFn` is required unless a default
65 * query function has been defined.
66 *
67 * The prefetch is skipped if the query already has any cached state β including
68 * a `pending`/`error` state left over from a previous attempt β so it won't
69 * refetch data that's already there or already in flight. It re-runs whenever a
70 * reactive dependency in `options` (built with `queryOptions`, for example)
71 * changes.
72 *
73 * Fire this during render, before a suspense boundary that wraps a component
74 * using `useQuery`'s `suspense()` β see the
75 * {@link https://tanstack.com/query/latest/docs/framework/vue/guides/suspense | Suspense guide}.
76 *
77 * @example
78 * ```vue
79 * <script setup lang="ts">
80 * import { usePrefetchQuery } from '@tanstack/vue-query'
81 * import Posts from './Posts.vue'
82 *
83 * // Fire the prefetch as soon as this component runs, before `Posts` mounts and calls `useQuery`.
84 * usePrefetchQuery({
85 * queryKey: ['posts'],
86 * queryFn: fetchPosts,
87 * })
88 * </script>
89 *
90 * <template>
91 * <Posts />
92 * </template>
93 * ```
94 *
95 * @param options - A `ref`, plain value, or reactive getter resolving to the
96 * {@link UsePrefetchQueryOptions} to use β everything you can pass to
97 * `queryClient.query`.
98 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the
99 * one provided by `VueQueryPlugin` will be used.
100 */
101export function usePrefetchQuery<
102 TQueryFnData = unknown,
103 TError = DefaultError,
104 TData = TQueryFnData,
105 TQueryData = TQueryFnData,
106 TQueryKey extends QueryKey = QueryKey,
107>(
108 options: MaybeRefOrGetter<
109 MaybeRefDeep<
110 UsePrefetchQueryOptions<
111 TQueryFnData,
112 TError,
113 TData,
114 TQueryData,
115 TQueryKey
116 >
117 >
118 >,
119 queryClient?: QueryClient,
120): void {
121 if (process.env.NODE_ENV === 'development') {
122 if (!getCurrentScope()) {
123 console.warn(
124 '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.',
125 )
126 }
127 }
128β
129 const client = queryClient || useQueryClient()
130β
131 watchEffect(() => {
132 const resolvedOptions = isGetter(options) ? options() : unref(options)
133 const clonedOptions: UsePrefetchQueryOptions<
134 TQueryFnData,
135 TError,
136 TData,
137 TQueryData,
138 TQueryKey
139 > = cloneDeepUnref(resolvedOptions)
140β
141 if (!client.getQueryState(clonedOptions.queryKey)) {
142 void client.query(clonedOptions).catch(noop)
143 }
144 })
145}