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

usePrefetchQuery.ts

69 lines1.8 KB

1import { getCurrentScope, unref, watchEffect } from 'vue-demi'
2import { useQueryClient } from './useQueryClient'
3import { cloneDeepUnref } from './utils'
4import type {
5 DefaultError,
6 FetchQueryOptions,
7 OmitKeyof,
8 QueryKey,
9 SkipToken,
10} from '@tanstack/query-core'
11import type { QueryClient } from './queryClient'
12import type { MaybeRefDeep, MaybeRefOrGetter } from './types'
13​
14export type UsePrefetchQueryOptions<
15 TQueryFnData,
16 TError,
17 TData,
18 TQueryKey extends QueryKey,
19> = OmitKeyof<
20 FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
21 'queryFn'
22> & {
23 queryFn?: Exclude<
24 FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
25 SkipToken
26 >
28​
29function isGetter<T>(value: MaybeRefOrGetter<T>): value is () => T {
30 return typeof value === 'function'
32​
33export function usePrefetchQuery<
34 TQueryFnData = unknown,
35 TError = DefaultError,
36 TData = TQueryFnData,
37 TQueryKey extends QueryKey = QueryKey,
38>(
39 options: MaybeRefOrGetter<
40 MaybeRefDeep<
41 UsePrefetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>
42 >
43 >,
44 queryClient?: QueryClient,
45): void {
46 if (process.env.NODE_ENV === 'development') {
47 if (!getCurrentScope()) {
48 console.warn(
49 '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.',
50 )
51 }
52 }
53​
54 const client = queryClient || useQueryClient()
55​
56 watchEffect(() => {
57 const resolvedOptions = isGetter(options) ? options() : unref(options)
58 const clonedOptions: UsePrefetchQueryOptions<
59 TQueryFnData,
60 TError,
61 TData,
62 TQueryKey
63 > = cloneDeepUnref(resolvedOptions)
64​
65 if (!client.getQueryState(clonedOptions.queryKey)) {
66 void client.prefetchQuery(clonedOptions)
67 }
68 })