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β
53/**
54 * Base implementation shared by `useQuery` and `useInfiniteQuery`.
55 *
56 * @param Observer - The observer class from query-core (`QueryObserver` or `InfiniteQueryObserver`).
57 * @param options - A `ref`, plain value, or reactive getter resolving to the query options.
58 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
59 * will be used.
60 */
61export function useBaseQuery<
62 TQueryFnData,
63 TError,
64 TData,
65 TQueryData,
66 TQueryKey extends QueryKey,
67 TPageParam,
68>(
69 Observer: typeof QueryObserver,
70 options: MaybeRefOrGetter<
71 UseQueryOptionsGeneric<
72 TQueryFnData,
73 TError,
74 TData,
75 TQueryData,
76 TQueryKey,
77 TPageParam
78 >
79 >,
80 queryClient?: QueryClient,
81): UseBaseQueryReturnType<TData, TError> {
82 if (process.env.NODE_ENV === 'development') {
83 if (!getCurrentScope()) {
84 console.warn(
85 '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.',
86 )
87 }
88 }
89β
90 const client = queryClient || useQueryClient()
91β
92 const defaultedOptions = computed(() => {
93 let resolvedOptions = options
94 if (typeof resolvedOptions === 'function') {
95 resolvedOptions = resolvedOptions()
96 }
97 const clonedOptions = cloneDeepUnref(resolvedOptions as any)
98β
99 if (typeof clonedOptions.enabled === 'function') {
100 clonedOptions.enabled = clonedOptions.enabled()
101 }
102β
103 const defaulted: DefaultedQueryObserverOptions<
104 TQueryFnData,
105 TError,
106 TData,
107 TQueryData,
108 TQueryKey
109 > = client.defaultQueryOptions(clonedOptions)
110β
111 defaulted._optimisticResults = client.isRestoring?.value
112 ? 'isRestoring'
113 : 'optimistic'
114β
115 return defaulted
116 })
117β
118 const observer = new Observer(client, defaultedOptions.value)
119 // @ts-expect-error
120 const state = defaultedOptions.value.shallow
121 ? shallowReactive(observer.getCurrentResult())
122 : reactive(observer.getCurrentResult())
123β
124 let unsubscribe = () => {
125 // noop
126 }
127β
128 if (client.isRestoring) {
129 watch(
130 client.isRestoring,
131 (isRestoring) => {
132 if (!isRestoring) {
133 unsubscribe()
134 unsubscribe = observer.subscribe((result) => {
135 updateState(state, result)
136 })
137 }
138 },
139 { immediate: true },
140 )
141 }
142β
143 const updater = () => {
144 observer.setOptions(defaultedOptions.value)
145 updateState(state, observer.getCurrentResult())
146 }
147β
148 watch(defaultedOptions, updater)
149β
150 onScopeDispose(() => {
151 unsubscribe()
152 })
153β
154 // fix #5910
155 const refetch = (...args: Parameters<(typeof state)['refetch']>) => {
156 updater()
157 return state.refetch(...args)
158 }
159β
160 const suspense = () => {
161 return new Promise<QueryObserverResult<TData, TError>>(
162 (resolve, reject) => {
163 let stopWatch = () => {
164 // noop
165 }
166 const run = () => {
167 if (defaultedOptions.value.enabled !== false) {
168 // fix #6133
169 observer.setOptions(defaultedOptions.value)
170 const optimisticResult = observer.getOptimisticResult(
171 defaultedOptions.value,
172 )
173 if (optimisticResult.isStale) {
174 stopWatch()
175 observer
176 .fetchOptimistic(defaultedOptions.value)
177 .then(resolve, (error: TError) => {
178 if (
179 shouldThrowError(defaultedOptions.value.throwOnError, [
180 error,
181 observer.getCurrentQuery(),
182 ])
183 ) {
184 reject(error)
185 } else {
186 resolve(observer.getCurrentResult())
187 }
188 })
189 } else {
190 stopWatch()
191 resolve(optimisticResult)
192 }
193 }
194 }
195β
196 run()
197β
198 stopWatch = watch(defaultedOptions, run)
199 },
200 )
201 }
202β
203 // Handle error boundary
204 watch(
205 () => state.error,
206 (error) => {
207 if (
208 state.isError &&
209 !state.isFetching &&
210 shouldThrowError(defaultedOptions.value.throwOnError, [
211 error as TError,
212 observer.getCurrentQuery(),
213 ])
214 ) {
215 throw error
216 }
217 },
218 )
219β
220 // @ts-expect-error
221 const readonlyState = defaultedOptions.value.shallow
222 ? shallowReadonly(state)
223 : readonly(state)
224β
225 const object: any = toRefs(readonlyState)
226 for (const key in state) {
227 if (typeof state[key as keyof typeof state] === 'function') {
228 object[key] = state[key as keyof typeof state]
229 }
230 }
231β
232 object.suspense = suspense
233 object.refetch = refetch
234β
235 return object as UseBaseQueryReturnType<TData, TError>
236}