Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useBaseQuery.ts

254 lines6.8 KB

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