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