Open History to see the last commit
1import {
2 computed,
3 getCurrentScope,
4 onScopeDispose,
5 reactive,
6 readonly,
7 toRefs,
8 unref,
9 watch,
10} from 'vue-demi'
11import { useQueryClient } from './useQueryClient'
12import {
13 cloneDeepUnref,
14 isQueryKey,
15 shouldThrowError,
16 updateState,
17} from './utils'
18import type { ToRef } from 'vue-demi'
19import type {
20 QueryFunction,
21 QueryKey,
22 QueryObserver,
23 QueryObserverOptions,
24 QueryObserverResult,
25} from '@tanstack/query-core'
26import type { DeepUnwrapRef, MaybeRef, WithQueryClientKey } from './types'
27import type { UseQueryOptions } from './useQuery'
28import type { UseInfiniteQueryOptions } from './useInfiniteQuery'
29β
30export type UseQueryReturnType<
31 TData,
32 TError,
33 Result = QueryObserverResult<TData, TError>,
34> = {
35 [K in keyof Result]: K extends
36 | 'fetchNextPage'
37 | 'fetchPreviousPage'
38 | 'refetch'
39 | 'remove'
40 ? Result[K]
41 : ToRef<Readonly<Result>[K]>
42} & {
43 suspense: () => Promise<Result>
44}
45β
46type UseQueryOptionsGeneric<
47 TQueryFnData,
48 TError,
49 TData,
50 TQueryKey extends QueryKey = QueryKey,
51> =
52 | UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>
53 | UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>
54β
55export function useBaseQuery<
56 TQueryFnData,
57 TError,
58 TData,
59 TQueryKey extends QueryKey,
60>(
61 Observer: typeof QueryObserver,
62 arg1:
63 | MaybeRef<TQueryKey>
64 | MaybeRef<UseQueryOptionsGeneric<TQueryFnData, TError, TData, TQueryKey>>,
65 arg2:
66 | MaybeRef<QueryFunction<TQueryFnData, DeepUnwrapRef<TQueryKey>>>
67 | MaybeRef<
68 UseQueryOptionsGeneric<TQueryFnData, TError, TData, TQueryKey>
69 > = {},
70 arg3: MaybeRef<
71 UseQueryOptionsGeneric<TQueryFnData, TError, TData, TQueryKey>
72 > = {},
73): UseQueryReturnType<TData, TError> {
74 if (process.env.NODE_ENV === 'development') {
75 if (!getCurrentScope()) {
76 console.warn(
77 'vue-query composables like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
78 )
79 }
80 }
81β
82 const options = computed(() => parseQueryArgs(arg1, arg2, arg3))
83β
84 const queryClient =
85 options.value.queryClient ?? useQueryClient(options.value.queryClientKey)
86β
87 const defaultedOptions = computed(() => {
88 const defaulted = queryClient.defaultQueryOptions(options.value)
89 defaulted._optimisticResults = queryClient.isRestoring.value
90 ? 'isRestoring'
91 : 'optimistic'
92β
93 return defaulted
94 })
95β
96 const observer = new Observer(queryClient, defaultedOptions.value)
97 const state = reactive(observer.getCurrentResult())
98β
99 let unsubscribe = () => {
100 // noop
101 }
102β
103 watch(
104 queryClient.isRestoring,
105 (isRestoring) => {
106 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
107 if (!isRestoring) {
108 unsubscribe()
109 unsubscribe = observer.subscribe((result) => {
110 updateState(state, result)
111 })
112 }
113 },
114 { immediate: true },
115 )
116β
117 const updater = () => {
118 observer.setOptions(defaultedOptions.value)
119 updateState(state, observer.getCurrentResult())
120 }
121β
122 watch(defaultedOptions, updater)
123β
124 onScopeDispose(() => {
125 unsubscribe()
126 })
127β
128 // fix #5910
129 const refetch = (...args: Parameters<typeof state['refetch']>) => {
130 updater()
131 return state.refetch(...args)
132 }
133β
134 const suspense = () => {
135 return new Promise<QueryObserverResult<TData, TError>>(
136 (resolve, reject) => {
137 let stopWatch = () => {
138 //noop
139 }
140 const run = () => {
141 if (defaultedOptions.value.enabled !== false) {
142 const optimisticResult = observer.getOptimisticResult(
143 defaultedOptions.value,
144 )
145 if (optimisticResult.isStale) {
146 stopWatch()
147 observer
148 .fetchOptimistic(defaultedOptions.value)
149 .then(resolve, reject)
150 } else {
151 stopWatch()
152 resolve(optimisticResult)
153 }
154 }
155 }
156β
157 run()
158β
159 stopWatch = watch(defaultedOptions, run)
160 },
161 )
162 }
163β
164 // Handle error boundary
165 watch(
166 () => state.error,
167 (error) => {
168 if (
169 state.isError &&
170 !state.isFetching &&
171 shouldThrowError(defaultedOptions.value.useErrorBoundary, [
172 error as TError,
173 observer.getCurrentQuery(),
174 ])
175 ) {
176 throw error
177 }
178 },
179 )
180β
181 const object: any = toRefs(readonly(state))
182 for (const key in state) {
183 if (typeof state[key as keyof typeof state] === 'function') {
184 object[key] = state[key as keyof typeof state]
185 }
186 }
187β
188 object.suspense = suspense
189 object.refetch = refetch
190β
191 return object as UseQueryReturnType<TData, TError>
192}
193β
194export function parseQueryArgs<
195 TQueryFnData = unknown,
196 TError = unknown,
197 TData = TQueryFnData,
198 TQueryData = TQueryFnData,
199 TQueryKey extends QueryKey = QueryKey,
200>(
201 arg1:
202 | MaybeRef<TQueryKey>
203 | MaybeRef<UseQueryOptionsGeneric<TQueryFnData, TError, TData, TQueryKey>>,
204 arg2:
205 | MaybeRef<QueryFunction<TQueryFnData, DeepUnwrapRef<TQueryKey>>>
206 | MaybeRef<
207 UseQueryOptionsGeneric<TQueryFnData, TError, TData, TQueryKey>
208 > = {},
209 arg3: MaybeRef<
210 UseQueryOptionsGeneric<TQueryFnData, TError, TData, TQueryKey>
211 > = {},
212): WithQueryClientKey<
213 QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
214> {
215 const plainArg1 = unref(arg1)
216 const plainArg2 = unref(arg2)
217 const plainArg3 = unref(arg3)
218β
219 let options = plainArg1
220β
221 if (!isQueryKey(plainArg1)) {
222 options = plainArg1
223 } else if (typeof plainArg2 === 'function') {
224 options = { ...plainArg3, queryKey: plainArg1, queryFn: plainArg2 }
225 } else {
226 options = { ...plainArg2, queryKey: plainArg1 }
227 }
228β
229 const clondedOptions = cloneDeepUnref(options)
230β
231 if (typeof clondedOptions.enabled === 'function') {
232 clondedOptions.enabled = clondedOptions.enabled()
233 }
234β
235 return clondedOptions as WithQueryClientKey<
236 QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
237 >
238}