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

useBaseQuery.ts

221 lines5.3 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 './useQuery'
24import type { UseInfiniteQueryOptions } from './useInfiniteQuery'
25​
26export type UseBaseQueryReturnType<
27 TData,
28 TError,
29 TResult = QueryObserverResult<TData, TError>,
30> = {
31 [K in keyof TResult]: K extends
32 | 'fetchNextPage'
33 | 'fetchPreviousPage'
34 | 'refetch'
35 ? TResult[K]
36 : Ref<Readonly<TResult>[K]>
37} & {
38 suspense: () => Promise<TResult>
40​
41type UseQueryOptionsGeneric<
42 TQueryFnData,
43 TError,
44 TData,
45 TQueryData,
46 TQueryKey extends QueryKey = QueryKey,
47 TPageParam = unknown,
48> =
49 | UseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
50 | UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>
51​
52export function useBaseQuery<
53 TQueryFnData,
54 TError,
55 TData,
56 TQueryData,
57 TQueryKey extends QueryKey,
58 TPageParam,
59>(
60 Observer: typeof QueryObserver,
61 options: UseQueryOptionsGeneric<
62 TQueryFnData,
63 TError,
64 TData,
65 TQueryData,
66 TQueryKey,
67 TPageParam
68 >,
69 queryClient?: QueryClient,
70): UseBaseQueryReturnType<TData, TError> {
71 if (process.env.NODE_ENV === 'development') {
72 if (!getCurrentScope()) {
73 console.warn(
74 '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.',
75 )
76 }
77 }
78​
79 const client = queryClient || useQueryClient()
80​
81 const defaultedOptions = computed(() => {
82 const clonedOptions = cloneDeepUnref(options as any)
83​
84 if (typeof clonedOptions.enabled === 'function') {
85 clonedOptions.enabled = clonedOptions.enabled()
86 }
87​
88 const defaulted: DefaultedQueryObserverOptions<
89 TQueryFnData,
90 TError,
91 TData,
92 TQueryData,
93 TQueryKey
94 > = client.defaultQueryOptions(clonedOptions)
95​
96 defaulted._optimisticResults = client.isRestoring?.value
97 ? 'isRestoring'
98 : 'optimistic'
99​
100 return defaulted
101 })
102​
103 const observer = new Observer(client, defaultedOptions.value)
104 // @ts-expect-error
105 const state = defaultedOptions.value.shallow
106 ? shallowReactive(observer.getCurrentResult())
107 : reactive(observer.getCurrentResult())
108​
109 let unsubscribe = () => {
110 // noop
111 }
112​
113 if (client.isRestoring) {
114 watch(
115 client.isRestoring,
116 (isRestoring) => {
117 if (!isRestoring) {
118 unsubscribe()
119 unsubscribe = observer.subscribe((result) => {
120 updateState(state, result)
121 })
122 }
123 },
124 { immediate: true },
125 )
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 // @ts-expect-error
206 const readonlyState = defaultedOptions.value.shallow
207 ? shallowReadonly(state)
208 : readonly(state)
209​
210 const object: any = toRefs(readonlyState)
211 for (const key in state) {
212 if (typeof state[key as keyof typeof state] === 'function') {
213 object[key] = state[key as keyof typeof state]
214 }
215 }
216​
217 object.suspense = suspense
218 object.refetch = refetch
219​
220 return object as UseBaseQueryReturnType<TData, TError>