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

usePrefetchQuery.ts

130 lines3.7 KB

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