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