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

useBaseQuery.ts

224 lines5.2 KB

1import {
2 computed,
3 getCurrentScope,
4 onScopeDispose,
5 readonly,
6 shallowReactive,
7 shallowReadonly,
8 toRefs,
9 watch,
10} from 'vue-demi'
11import { useQueryClient } from './useQueryClient'
12import { cloneDeepUnref, shouldThrowError, updateState } from './utils'
13import type { Ref } from 'vue-demi'
14import type {
15 DefaultedQueryObserverOptions,
16 QueryKey,
17 QueryObserver,
18 QueryObserverResult,
19} from '@tanstack/query-core'
20import type { QueryClient } from './queryClient'
21import type { UseQueryOptions } from './useQuery'
22import type { UseInfiniteQueryOptions } from './useInfiniteQuery'
23​
24export type UseBaseQueryReturnType<
25 TData,
26 TError,
27 TResult = QueryObserverResult<TData, TError>,
28> = {
29 [K in keyof TResult]: K extends
30 | 'fetchNextPage'
31 | 'fetchPreviousPage'
32 | 'refetch'
33 ? TResult[K]
34 : Ref<Readonly<TResult>[K]>
35} & {
36 suspense: () => Promise<TResult>
38​
39type UseQueryOptionsGeneric<
40 TQueryFnData,
41 TError,
42 TData,
43 TQueryData,
44 TQueryKey extends QueryKey = QueryKey,
45 TPageParam = unknown,
46> =
47 | UseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
48 | UseInfiniteQueryOptions<
49 TQueryFnData,
50 TError,
51 TData,
52 TQueryData,
53 TQueryKey,
54 TPageParam
55 >
56​
57export function useBaseQuery<
58 TQueryFnData,
59 TError,
60 TData,
61 TQueryData,
62 TQueryKey extends QueryKey,
63 TPageParam,
64>(
65 Observer: typeof QueryObserver,
66 options: UseQueryOptionsGeneric<
67 TQueryFnData,
68 TError,
69 TData,
70 TQueryData,
71 TQueryKey,
72 TPageParam
73 >,
74 queryClient?: QueryClient,
75): UseBaseQueryReturnType<TData, TError> {
76 if (process.env.NODE_ENV === 'development') {
77 if (!getCurrentScope()) {
78 console.warn(
79 '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.',
80 )
81 }
82 }
83​
84 const client = queryClient || useQueryClient()
85​
86 const defaultedOptions = computed(() => {
87 const clonedOptions = cloneDeepUnref(options as any)
88​
89 if (typeof clonedOptions.enabled === 'function') {
90 clonedOptions.enabled = clonedOptions.enabled()
91 }
92​
93 const defaulted: DefaultedQueryObserverOptions<
94 TQueryFnData,
95 TError,
96 TData,
97 TQueryData,
98 TQueryKey
99 > = client.defaultQueryOptions(clonedOptions)
100​
101 defaulted._optimisticResults = client.isRestoring.value
102 ? 'isRestoring'
103 : 'optimistic'
104​
105 return defaulted
106 })
107​
108 const observer = new Observer(client, defaultedOptions.value)
109 const state = shallowReactive(observer.getCurrentResult())
110​
111 let unsubscribe = () => {
112 // noop
113 }
114​
115 watch(
116 client.isRestoring,
117 (isRestoring) => {
118 if (!isRestoring) {
119 unsubscribe()
120 unsubscribe = observer.subscribe((result) => {
121 updateState(state, result)
122 })
123 }
124 },
125 { immediate: true },
126 )
127​
128 const updater = () => {
129 observer.setOptions(defaultedOptions.value)
130 updateState(state, observer.getCurrentResult())
131 }
132​
133 watch(defaultedOptions, updater)
134​
135 onScopeDispose(() => {
136 unsubscribe()
137 })
138​
139 // fix #5910
140 const refetch = (...args: Parameters<(typeof state)['refetch']>) => {
141 updater()
142 return state.refetch(...args)
143 }
144​
145 const suspense = () => {
146 return new Promise<QueryObserverResult<TData, TError>>(
147 (resolve, reject) => {
148 let stopWatch = () => {
149 // noop
150 }
151 const run = () => {
152 if (defaultedOptions.value.enabled !== false) {
153 // fix #6133
154 observer.setOptions(defaultedOptions.value)
155 const optimisticResult = observer.getOptimisticResult(
156 defaultedOptions.value,
157 )
158 if (optimisticResult.isStale) {
159 stopWatch()
160 observer
161 .fetchOptimistic(defaultedOptions.value)
162 .then(resolve, (error: TError) => {
163 if (
164 shouldThrowError(defaultedOptions.value.throwOnError, [
165 error,
166 observer.getCurrentQuery(),
167 ])
168 ) {
169 reject(error)
170 } else {
171 resolve(observer.getCurrentResult())
172 }
173 })
174 } else {
175 stopWatch()
176 resolve(optimisticResult)
177 }
178 }
179 }
180​
181 run()
182​
183 stopWatch = watch(defaultedOptions, run)
184 },
185 )
186 }
187​
188 // Handle error boundary
189 watch(
190 () => state.error,
191 (error) => {
192 if (
193 state.isError &&
194 !state.isFetching &&
195 shouldThrowError(defaultedOptions.value.throwOnError, [
196 error as TError,
197 observer.getCurrentQuery(),
198 ])
199 ) {
200 throw error
201 }
202 },
203 )
204​
205 const readonlyState =
206 process.env.NODE_ENV === 'production'
207 ? state
208 : // @ts-expect-error
209 defaultedOptions.value.shallow
210 ? shallowReadonly(state)
211 : readonly(state)
212​
213 const object: any = toRefs(readonlyState)
214 for (const key in state) {
215 if (typeof state[key as keyof typeof state] === 'function') {
216 object[key] = state[key as keyof typeof state]
217 }
218 }
219​
220 object.suspense = suspense
221 object.refetch = refetch
222​
223 return object as UseBaseQueryReturnType<TData, TError>