Open History to see the last commit
1import { shouldThrowError } from '@tanstack/query-core'
2import {
3 computed,
4 getCurrentScope,
5 onScopeDispose,
6 reactive,
7 readonly,
8 shallowReactive,
9 shallowReadonly,
10 toRefs,
11 watch,
12} from 'vue-demi'
13import { useQueryClient } from './useQueryClient'
14import { cloneDeepUnref, updateState } from './utils'
15import type {
16 DefaultedQueryObserverOptions,
17 QueryKey,
18 QueryObserver,
19 QueryObserverResult,
20} from '@tanstack/query-core'
21import type { Ref } from 'vue-demi'
22import type { QueryClient } from './queryClient'
23import type { UseQueryOptions } from './queryOptions'
24import type { MaybeRefOrGetter } from './types'
25import type { UseInfiniteQueryOptions } from './useInfiniteQuery'
26β
27/**
28 * Readonly view of a union that stays a union. A single `Readonly<Union>` collapses the members, which
29 * drops the `status` / `isSuccess` / `isPending` discriminants.
30 */
31type ReadonlyQueryState<T> = T extends any
32 ? { readonly [K in keyof T]: T[K] }
33 : never
34β
35/**
36 * The result of the query composables: every property of the observer result wrapped in a `Ref`, except
37 * the `refetch`, `fetchNextPage`, and `fetchPreviousPage` functions, plus `suspense` and `state`.
38 */
39export type UseBaseQueryReturnType<
40 TData,
41 TError,
42 TResult = QueryObserverResult<TData, TError>,
43> = {
44 [K in keyof TResult]: K extends
45 | 'fetchNextPage'
46 | 'fetchPreviousPage'
47 | 'refetch'
48 ? TResult[K]
49 : Ref<Readonly<TResult>[K]>
50} & {
51 /**
52 * Returns a promise for use with Vue's `Suspense` or `onServerPrefetch`. It fetches the query if it has no
53 * data or its data is stale and resolves with the result once that fetch resolves (usually when the query
54 * function finishes, but earlier after the first chunk of a streamed query or when data is set during the
55 * fetch), or resolves immediately if the data is fresh. While the query is disabled, it waits until the query
56 * is enabled. If the fetch fails, it resolves with the error result, unless `throwOnError` is (or returns)
57 * `true`, in which case it rejects.
58 */
59 suspense: () => Promise<TResult>
60 /**
61 * The query result as one readonly reactive object. `data`, `error`, `status`, `isPending`, and the other
62 * fields are plain values β read `state.data`, not `state.data.value`.
63 *
64 * The object is a discriminated union, so a check on `status`, `isSuccess`, `isPending`, or `isError`
65 * narrows the other fields. When `status` is `'success'` (or `isSuccess` is `true`), `data` is `TData`.
66 * When `status` is `'pending'` (or `isPending` is `true`), `data` is `undefined` and `error` is `null`.
67 * @example
68 * ```vue
69 * <script setup lang="ts">
70 * import { useQuery } from '@tanstack/vue-query'
71 *
72 * const { state } = useQuery({
73 * queryKey: ['post'],
74 * queryFn: fetchPost,
75 * })
76 *
77 * if (state.status === 'success') {
78 * // `state.data` is `Post`, not `Post | undefined`
79 * console.log(state.data.title)
80 * }
81 * </script>
82 *
83 * <template>
84 * <span v-if="state.status === 'pending'">Loading...</span>
85 * <span v-else-if="state.status === 'error'">Error: {{ state.error.message }}</span>
86 * <h1 v-else>{{ state.data.title }}</h1>
87 * </template>
88 * ```
89 */
90 state: ReadonlyQueryState<TResult>
91}
92β
93type UseQueryOptionsGeneric<
94 TQueryFnData,
95 TError,
96 TData,
97 TQueryData,
98 TQueryKey extends QueryKey = QueryKey,
99 TPageParam = unknown,
100> =
101 | UseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
102 | UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>
103β
104/**
105 * Base implementation shared by `useQuery` and `useInfiniteQuery`.
106 * @param Observer - The observer class from query-core (`QueryObserver` or `InfiniteQueryObserver`).
107 * @param options - A `ref`, plain value, or reactive getter resolving to the query options.
108 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
109 * will be used.
110 * @returns The query result as `ref`s, plus the `suspense` function.
111 */
112export function useBaseQuery<
113 TQueryFnData,
114 TError,
115 TData,
116 TQueryData,
117 TQueryKey extends QueryKey,
118 TPageParam,
119>(
120 Observer: typeof QueryObserver,
121 options: MaybeRefOrGetter<
122 UseQueryOptionsGeneric<
123 TQueryFnData,
124 TError,
125 TData,
126 TQueryData,
127 TQueryKey,
128 TPageParam
129 >
130 >,
131 queryClient?: QueryClient,
132): UseBaseQueryReturnType<TData, TError> {
133 if (process.env.NODE_ENV === 'development') {
134 if (!getCurrentScope()) {
135 console.warn(
136 '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.',
137 )
138 }
139 }
140β
141 const client = queryClient || useQueryClient()
142β
143 const defaultedOptions = computed(() => {
144 let resolvedOptions = options
145 if (typeof resolvedOptions === 'function') {
146 resolvedOptions = resolvedOptions()
147 }
148 const clonedOptions = cloneDeepUnref(resolvedOptions as any)
149β
150 // A zero-arg function is a Vue getter and must run here so its refs are tracked.
151 // `(query) => boolean` is query-core's callback and is left for core to call.
152 if (
153 typeof clonedOptions.enabled === 'function' &&
154 clonedOptions.enabled.length === 0
155 ) {
156 clonedOptions.enabled = clonedOptions.enabled()
157 }
158β
159 const defaulted: DefaultedQueryObserverOptions<
160 TQueryFnData,
161 TError,
162 TData,
163 TQueryData,
164 TQueryKey
165 > = client.defaultQueryOptions(clonedOptions)
166β
167 defaulted._optimisticResults = client.isRestoring?.value
168 ? 'isRestoring'
169 : 'optimistic'
170β
171 return defaulted
172 })
173β
174 const observer = new Observer(client, defaultedOptions.value)
175 // @ts-expect-error
176 const state = defaultedOptions.value.shallow
177 ? shallowReactive(observer.getCurrentResult())
178 : reactive(observer.getCurrentResult())
179β
180 let unsubscribe = () => {
181 // noop
182 }
183β
184 // Replaced below with the wrapper. Declared here so the subscriber can put it
185 // back after `updateState` copies the observer's own `refetch` onto `state`.
186 let refetch: (typeof state)['refetch'] = (...args) =>
187 observer.refetch(...args)
188β
189 if (client.isRestoring) {
190 watch(
191 client.isRestoring,
192 (isRestoring) => {
193 if (!isRestoring) {
194 unsubscribe()
195 unsubscribe = observer.subscribe((result) => {
196 updateState(state, result)
197 state.refetch = refetch
198 })
199 }
200 },
201 { immediate: true },
202 )
203 }
204β
205 const updater = () => {
206 observer.setOptions(defaultedOptions.value)
207 updateState(state, observer.getCurrentResult())
208 state.refetch = refetch
209 }
210β
211 watch(defaultedOptions, updater)
212β
213 onScopeDispose(() => {
214 unsubscribe()
215 })
216β
217 // fix #5910. Call `observer.refetch`: `state.refetch` is this wrapper, so
218 // calling it would recurse.
219 refetch = (...args) => {
220 updater()
221 return observer.refetch(...args)
222 }
223 state.refetch = refetch
224β
225 const suspense = () => {
226 return new Promise<QueryObserverResult<TData, TError>>(
227 (resolve, reject) => {
228 let stopWatch = () => {
229 // noop
230 }
231 const run = () => {
232 // Apply the latest options before resolving `enabled`, so a query callback sees the current query.
233 // fix #6133
234 observer.setOptions(defaultedOptions.value)
235 const { enabled } = defaultedOptions.value
236 if (
237 (typeof enabled === 'function'
238 ? enabled(observer.getCurrentQuery())
239 : enabled) !== false
240 ) {
241 const optimisticResult = observer.getOptimisticResult(
242 defaultedOptions.value,
243 )
244 if (optimisticResult.isStale) {
245 stopWatch()
246 observer
247 .fetchOptimistic(defaultedOptions.value)
248 .then(resolve, (error: TError) => {
249 if (
250 shouldThrowError(defaultedOptions.value.throwOnError, [
251 error,
252 observer.getCurrentQuery(),
253 ])
254 ) {
255 reject(error)
256 } else {
257 resolve(observer.getCurrentResult())
258 }
259 })
260 } else {
261 stopWatch()
262 resolve(optimisticResult)
263 }
264 }
265 }
266β
267 run()
268β
269 stopWatch = watch(defaultedOptions, run)
270 },
271 )
272 }
273β
274 // Handle error boundary
275 watch(
276 () => state.error,
277 (error) => {
278 if (
279 state.isError &&
280 !state.isFetching &&
281 shouldThrowError(defaultedOptions.value.throwOnError, [
282 error as TError,
283 observer.getCurrentQuery(),
284 ])
285 ) {
286 throw error
287 }
288 },
289 )
290β
291 // @ts-expect-error
292 const readonlyState = defaultedOptions.value.shallow
293 ? shallowReadonly(state)
294 : readonly(state)
295β
296 const object: any = toRefs(readonlyState)
297 for (const key in state) {
298 if (typeof state[key as keyof typeof state] === 'function') {
299 object[key] = state[key as keyof typeof state]
300 }
301 }
302β
303 object.suspense = suspense
304 object.refetch = refetch
305 object.state = readonlyState
306β
307 return object as UseBaseQueryReturnType<TData, TError>
308}