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