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 './queryOptions'
24import type { UseInfiniteQueryOptions } from './useInfiniteQuery'
25import type { MaybeRefOrGetter } from './types'
26β
27/**
28 * The result of the query composables: every property of the observer result wrapped in a `Ref`, except
29 * the `refetch`, `fetchNextPage`, and `fetchPreviousPage` functions, plus `suspense`.
30 */
31export type UseBaseQueryReturnType<
32 TData,
33 TError,
34 TResult = QueryObserverResult<TData, TError>,
35> = {
36 [K in keyof TResult]: K extends
37 | 'fetchNextPage'
38 | 'fetchPreviousPage'
39 | 'refetch'
40 ? TResult[K]
41 : Ref<Readonly<TResult>[K]>
42} & {
43 /**
44 * Returns a promise for use with Vue's `Suspense` or `onServerPrefetch`. It fetches the query if it has no
45 * data or its data is stale and resolves with the result once that fetch resolves (usually when the query
46 * function finishes, but earlier after the first chunk of a streamed query or when data is set during the
47 * fetch), or resolves immediately if the data is fresh. While the query is disabled, it waits until the query
48 * is enabled. If the fetch fails, it resolves with the error result, unless `throwOnError` is (or returns)
49 * `true`, in which case it rejects.
50 */
51 suspense: () => Promise<TResult>
52}
53β
54type UseQueryOptionsGeneric<
55 TQueryFnData,
56 TError,
57 TData,
58 TQueryData,
59 TQueryKey extends QueryKey = QueryKey,
60 TPageParam = unknown,
61> =
62 | UseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
63 | UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>
64β
65/**
66 * Base implementation shared by `useQuery` and `useInfiniteQuery`.
67 * @param Observer - The observer class from query-core (`QueryObserver` or `InfiniteQueryObserver`).
68 * @param options - A `ref`, plain value, or reactive getter resolving to the query options.
69 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
70 * will be used.
71 * @returns The query result as `ref`s, plus the `suspense` function.
72 */
73export function useBaseQuery<
74 TQueryFnData,
75 TError,
76 TData,
77 TQueryData,
78 TQueryKey extends QueryKey,
79 TPageParam,
80>(
81 Observer: typeof QueryObserver,
82 options: MaybeRefOrGetter<
83 UseQueryOptionsGeneric<
84 TQueryFnData,
85 TError,
86 TData,
87 TQueryData,
88 TQueryKey,
89 TPageParam
90 >
91 >,
92 queryClient?: QueryClient,
93): UseBaseQueryReturnType<TData, TError> {
94 if (process.env.NODE_ENV === 'development') {
95 if (!getCurrentScope()) {
96 console.warn(
97 '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.',
98 )
99 }
100 }
101β
102 const client = queryClient || useQueryClient()
103β
104 const defaultedOptions = computed(() => {
105 let resolvedOptions = options
106 if (typeof resolvedOptions === 'function') {
107 resolvedOptions = resolvedOptions()
108 }
109 const clonedOptions = cloneDeepUnref(resolvedOptions as any)
110β
111 if (typeof clonedOptions.enabled === 'function') {
112 clonedOptions.enabled = clonedOptions.enabled()
113 }
114β
115 const defaulted: DefaultedQueryObserverOptions<
116 TQueryFnData,
117 TError,
118 TData,
119 TQueryData,
120 TQueryKey
121 > = client.defaultQueryOptions(clonedOptions)
122β
123 defaulted._optimisticResults = client.isRestoring?.value
124 ? 'isRestoring'
125 : 'optimistic'
126β
127 return defaulted
128 })
129β
130 const observer = new Observer(client, defaultedOptions.value)
131 // @ts-expect-error
132 const state = defaultedOptions.value.shallow
133 ? shallowReactive(observer.getCurrentResult())
134 : reactive(observer.getCurrentResult())
135β
136 let unsubscribe = () => {
137 // noop
138 }
139β
140 if (client.isRestoring) {
141 watch(
142 client.isRestoring,
143 (isRestoring) => {
144 if (!isRestoring) {
145 unsubscribe()
146 unsubscribe = observer.subscribe((result) => {
147 updateState(state, result)
148 })
149 }
150 },
151 { immediate: true },
152 )
153 }
154β
155 const updater = () => {
156 observer.setOptions(defaultedOptions.value)
157 updateState(state, observer.getCurrentResult())
158 }
159β
160 watch(defaultedOptions, updater)
161β
162 onScopeDispose(() => {
163 unsubscribe()
164 })
165β
166 // fix #5910
167 const refetch = (...args: Parameters<(typeof state)['refetch']>) => {
168 updater()
169 return state.refetch(...args)
170 }
171β
172 const suspense = () => {
173 return new Promise<QueryObserverResult<TData, TError>>(
174 (resolve, reject) => {
175 let stopWatch = () => {
176 // noop
177 }
178 const run = () => {
179 if (defaultedOptions.value.enabled !== false) {
180 // fix #6133
181 observer.setOptions(defaultedOptions.value)
182 const optimisticResult = observer.getOptimisticResult(
183 defaultedOptions.value,
184 )
185 if (optimisticResult.isStale) {
186 stopWatch()
187 observer
188 .fetchOptimistic(defaultedOptions.value)
189 .then(resolve, (error: TError) => {
190 if (
191 shouldThrowError(defaultedOptions.value.throwOnError, [
192 error,
193 observer.getCurrentQuery(),
194 ])
195 ) {
196 reject(error)
197 } else {
198 resolve(observer.getCurrentResult())
199 }
200 })
201 } else {
202 stopWatch()
203 resolve(optimisticResult)
204 }
205 }
206 }
207β
208 run()
209β
210 stopWatch = watch(defaultedOptions, run)
211 },
212 )
213 }
214β
215 // Handle error boundary
216 watch(
217 () => state.error,
218 (error) => {
219 if (
220 state.isError &&
221 !state.isFetching &&
222 shouldThrowError(defaultedOptions.value.throwOnError, [
223 error as TError,
224 observer.getCurrentQuery(),
225 ])
226 ) {
227 throw error
228 }
229 },
230 )
231β
232 // @ts-expect-error
233 const readonlyState = defaultedOptions.value.shallow
234 ? shallowReadonly(state)
235 : readonly(state)
236β
237 const object: any = toRefs(readonlyState)
238 for (const key in state) {
239 if (typeof state[key as keyof typeof state] === 'function') {
240 object[key] = state[key as keyof typeof state]
241 }
242 }
243β
244 object.suspense = suspense
245 object.refetch = refetch
246β
247 return object as UseBaseQueryReturnType<TData, TError>
248}