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 const clonedOptions = cloneDeepUnref(options as any)
86β
87 if (typeof clonedOptions.enabled === 'function') {
88 clonedOptions.enabled = clonedOptions.enabled()
89 }
90β
91 const defaulted: DefaultedQueryObserverOptions<
92 TQueryFnData,
93 TError,
94 TData,
95 TQueryData,
96 TQueryKey
97 > = client.defaultQueryOptions(clonedOptions)
98β
99 defaulted._optimisticResults = client.isRestoring?.value
100 ? 'isRestoring'
101 : 'optimistic'
102β
103 return defaulted
104 })
105β
106 const observer = new Observer(client, defaultedOptions.value)
107 // @ts-expect-error
108 const state = defaultedOptions.value.shallow
109 ? shallowReactive(observer.getCurrentResult())
110 : reactive(observer.getCurrentResult())
111β
112 let unsubscribe = () => {
113 // noop
114 }
115β
116 if (client.isRestoring) {
117 watch(
118 client.isRestoring,
119 (isRestoring) => {
120 if (!isRestoring) {
121 unsubscribe()
122 unsubscribe = observer.subscribe((result) => {
123 updateState(state, result)
124 })
125 }
126 },
127 { immediate: true },
128 )
129 }
130β
131 const updater = () => {
132 observer.setOptions(defaultedOptions.value)
133 updateState(state, observer.getCurrentResult())
134 }
135β
136 watch(defaultedOptions, updater)
137β
138 onScopeDispose(() => {
139 unsubscribe()
140 })
141β
142 // fix #5910
143 const refetch = (...args: Parameters<(typeof state)['refetch']>) => {
144 updater()
145 return state.refetch(...args)
146 }
147β
148 const suspense = () => {
149 return new Promise<QueryObserverResult<TData, TError>>(
150 (resolve, reject) => {
151 let stopWatch = () => {
152 // noop
153 }
154 const run = () => {
155 if (defaultedOptions.value.enabled !== false) {
156 // fix #6133
157 observer.setOptions(defaultedOptions.value)
158 const optimisticResult = observer.getOptimisticResult(
159 defaultedOptions.value,
160 )
161 if (optimisticResult.isStale) {
162 stopWatch()
163 observer
164 .fetchOptimistic(defaultedOptions.value)
165 .then(resolve, (error: TError) => {
166 if (
167 shouldThrowError(defaultedOptions.value.throwOnError, [
168 error,
169 observer.getCurrentQuery(),
170 ])
171 ) {
172 reject(error)
173 } else {
174 resolve(observer.getCurrentResult())
175 }
176 })
177 } else {
178 stopWatch()
179 resolve(optimisticResult)
180 }
181 }
182 }
183β
184 run()
185β
186 stopWatch = watch(defaultedOptions, run)
187 },
188 )
189 }
190β
191 // Handle error boundary
192 watch(
193 () => state.error,
194 (error) => {
195 if (
196 state.isError &&
197 !state.isFetching &&
198 shouldThrowError(defaultedOptions.value.throwOnError, [
199 error as TError,
200 observer.getCurrentQuery(),
201 ])
202 ) {
203 throw error
204 }
205 },
206 )
207β
208 // @ts-expect-error
209 const readonlyState = defaultedOptions.value.shallow
210 ? shallowReadonly(state)
211 : readonly(state)
212β
213 const object: any = toRefs(readonlyState)
214 for (const key in state) {
215 if (typeof state[key as keyof typeof state] === 'function') {
216 object[key] = state[key as keyof typeof state]
217 }
218 }
219β
220 object.suspense = suspense
221 object.refetch = refetch
222β
223 return object as UseBaseQueryReturnType<TData, TError>
224}