Open History to see the last commit
1import { QueriesObserver } from '@tanstack/query-core'
2import {
3 computed,
4 getCurrentScope,
5 onScopeDispose,
6 readonly,
7 shallowReadonly,
8 shallowRef,
9 unref,
10 watch,
11} from 'vue-demi'
12import { useQueryClient } from './useQueryClient'
13import { cloneDeepUnref } from './utils'
14import type {
15 DefaultError,
16 DefinedQueryObserverResult,
17 QueriesObserverOptions,
18 QueryFunction,
19 QueryKey,
20 QueryObserverResult,
21 ThrowOnError,
22} from '@tanstack/query-core'
23import type { Ref } from 'vue-demi'
24import type { QueryClient } from './queryClient'
25import type { UseQueryOptions } from './queryOptions'
26import type { DeepUnwrapRef, MaybeRefDeep, ShallowOption } from './types'
27β
28// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.
29// `placeholderData` function does not have a parameter
30type UseQueryOptionsForUseQueries<
31 TQueryFnData = unknown,
32 TError = unknown,
33 TData = TQueryFnData,
34 TQueryKey extends QueryKey = QueryKey,
35> = UseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>
36β
37// Avoid TS depth-limit error in case of large array literal
38type MAXIMUM_DEPTH = 20
39β
40// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
41type SkipTokenForUseQueries = symbol
42β
43type GetUseQueryOptionsForUseQueries<T> =
44 // Part 1: if UseQueryOptions are already being sent through, then just return T
45 T extends UseQueryOptions
46 ? DeepUnwrapRef<T>
47 : // Part 2: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
48 T extends {
49 queryFnData: infer TQueryFnData
50 error?: infer TError
51 data: infer TData
52 }
53 ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
54 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
55 ? UseQueryOptionsForUseQueries<TQueryFnData, TError>
56 : T extends { data: infer TData; error?: infer TError }
57 ? UseQueryOptionsForUseQueries<unknown, TError, TData>
58 : // Part 3: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]
59 T extends [infer TQueryFnData, infer TError, infer TData]
60 ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
61 : T extends [infer TQueryFnData, infer TError]
62 ? UseQueryOptionsForUseQueries<TQueryFnData, TError>
63 : T extends [infer TQueryFnData]
64 ? UseQueryOptionsForUseQueries<TQueryFnData>
65 : // Part 4: responsible for inferring and enforcing type if no explicit parameter was provided
66 T extends {
67 queryFn?:
68 | QueryFunction<infer TQueryFnData, infer TQueryKey>
69 | SkipTokenForUseQueries
70 select?: (data: any) => infer TData
71 throwOnError?: ThrowOnError<any, infer TError, any, any>
72 }
73 ? UseQueryOptionsForUseQueries<
74 TQueryFnData,
75 unknown extends TError ? DefaultError : TError,
76 unknown extends TData ? TQueryFnData : TData,
77 TQueryKey
78 >
79 : T extends {
80 queryFn?:
81 | QueryFunction<infer TQueryFnData, infer TQueryKey>
82 | SkipTokenForUseQueries
83 throwOnError?: ThrowOnError<any, infer TError, any, any>
84 }
85 ? UseQueryOptionsForUseQueries<
86 TQueryFnData,
87 TError,
88 TQueryFnData,
89 TQueryKey
90 >
91 : // Fallback
92 UseQueryOptionsForUseQueries
93β
94// A defined initialData setting should return a DefinedQueryObserverResult rather than QueryObserverResult
95type GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {
96 initialData?: infer TInitialData
97}
98 ? unknown extends TInitialData
99 ? QueryObserverResult<TData, TError>
100 : TInitialData extends TData
101 ? DefinedQueryObserverResult<TData, TError>
102 : TInitialData extends () => infer TInitialDataResult
103 ? unknown extends TInitialDataResult
104 ? QueryObserverResult<TData, TError>
105 : TInitialDataResult extends TData
106 ? DefinedQueryObserverResult<TData, TError>
107 : QueryObserverResult<TData, TError>
108 : QueryObserverResult<TData, TError>
109 : QueryObserverResult<TData, TError>
110β
111type GetUseQueryResult<T> =
112 // Part 1: if using UseQueryOptions then the types are already set
113 T extends UseQueryOptions<
114 infer TQueryFnData,
115 infer TError,
116 infer TData,
117 any,
118 any
119 >
120 ? GetDefinedOrUndefinedQueryResult<
121 T,
122 undefined extends TData ? TQueryFnData : TData,
123 unknown extends TError ? DefaultError : TError
124 >
125 : // Part 2: responsible for mapping explicit type parameter to function result, if object
126 T extends { queryFnData: any; error?: infer TError; data: infer TData }
127 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
128 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
129 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
130 : T extends { data: infer TData; error?: infer TError }
131 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
132 : // Part 3: responsible for mapping explicit type parameter to function result, if tuple
133 T extends [any, infer TError, infer TData]
134 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
135 : T extends [infer TQueryFnData, infer TError]
136 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
137 : T extends [infer TQueryFnData]
138 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>
139 : // Part 4: responsible for mapping inferred type to results, if no explicit parameter was provided
140 T extends {
141 queryFn?:
142 | QueryFunction<infer TQueryFnData, any>
143 | SkipTokenForUseQueries
144 select?: (data: any) => infer TData
145 throwOnError?: ThrowOnError<any, infer TError, any, any>
146 }
147 ? GetDefinedOrUndefinedQueryResult<
148 T,
149 unknown extends TData ? TQueryFnData : TData,
150 unknown extends TError ? DefaultError : TError
151 >
152 : T extends {
153 queryFn?:
154 | QueryFunction<infer TQueryFnData, any>
155 | SkipTokenForUseQueries
156 throwOnError?: ThrowOnError<any, infer TError, any, any>
157 }
158 ? GetDefinedOrUndefinedQueryResult<
159 T,
160 TQueryFnData,
161 unknown extends TError ? DefaultError : TError
162 >
163 : // Fallback
164 QueryObserverResult
165β
166/**
167 * UseQueriesOptions reducer recursively unwraps function arguments to infer/enforce type param
168 */
169export type UseQueriesOptions<
170 T extends Array<any>,
171 TResults extends Array<any> = [],
172 TDepth extends ReadonlyArray<number> = [],
173> = TDepth['length'] extends MAXIMUM_DEPTH
174 ? Array<UseQueryOptionsForUseQueries>
175 : T extends []
176 ? []
177 : T extends [infer Head]
178 ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]
179 : T extends [infer Head, ...infer Tails]
180 ? UseQueriesOptions<
181 [...Tails],
182 [...TResults, GetUseQueryOptionsForUseQueries<Head>],
183 [...TDepth, 1]
184 >
185 : ReadonlyArray<unknown> extends T
186 ? T
187 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
188 // use this to infer the param types in the case of Array.map() argument
189 T extends Array<
190 UseQueryOptionsForUseQueries<
191 infer TQueryFnData,
192 infer TError,
193 infer TData,
194 infer TQueryKey
195 >
196 >
197 ? Array<
198 UseQueryOptionsForUseQueries<
199 TQueryFnData,
200 TError,
201 TData,
202 TQueryKey
203 >
204 >
205 : // Fallback
206 Array<UseQueryOptionsForUseQueries>
207β
208/**
209 * UseQueriesResults reducer recursively maps type param to results
210 */
211export type UseQueriesResults<
212 T extends Array<any>,
213 TResults extends Array<any> = [],
214 TDepth extends ReadonlyArray<number> = [],
215> = TDepth['length'] extends MAXIMUM_DEPTH
216 ? Array<QueryObserverResult>
217 : T extends []
218 ? []
219 : T extends [infer Head]
220 ? [...TResults, GetUseQueryResult<Head>]
221 : T extends [infer Head, ...infer Tails]
222 ? UseQueriesResults<
223 [...Tails],
224 [...TResults, GetUseQueryResult<Head>],
225 [...TDepth, 1]
226 >
227 : { [K in keyof T]: GetUseQueryResult<T[K]> }
228β
229type UseQueriesOptionsArg<T extends Array<any>> = readonly [
230 ...UseQueriesOptions<T>,
231]
232β
233/**
234 * The `useQueries` composable can be used to fetch a variable number of queries.
235 *
236 * The `queries` option accepts an array of query option objects mostly identical to `useQuery`'s. It may be a
237 * plain array, a `ref`/reactive array (each entry tracked individually), or a getter function β pass a getter
238 * if the array itself (its length, or which queries are in it) depends on other reactive state.
239 *
240 * Having the same query key more than once in the array of query objects may cause some data to be shared
241 * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
242 * structure.
243 *
244 * The `combine` option can be used to combine the results of the queries into a single value. The result will
245 * be structurally shared to be as referentially stable as possible.
246 *
247 * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
248 * previously rendered queries, because the number of queries can differ between renders.
249 * @param options - The `queries` array to run, and the optional `combine` and `shallow` options.
250 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
251 * will be used.
252 * @returns A `ref` to the combined result. Without `combine`, this is an array with all the query results, in
253 * the same order as the input. When `combine` is provided, this is the value returned by `combine` instead.
254 * @example
255 * ```vue
256 * <script setup lang="ts">
257 * import { useQueries } from '@tanstack/vue-query'
258 *
259 * const props = defineProps<{ ids: Array<number> }>()
260 *
261 * const postQueries = useQueries({
262 * queries: () =>
263 * props.ids.map((id) => ({
264 * queryKey: ['post', id],
265 * queryFn: () => fetchPost(id),
266 * staleTime: Infinity,
267 * })),
268 * })
269 * </script>
270 *
271 * <template>
272 * <ul>
273 * <li v-for="(query, index) in postQueries" :key="props.ids[index]">
274 * <span v-if="query.isPending">Loading...</span>
275 * <span v-else-if="query.isError">Error: {{ query.error.message }}</span>
276 * <span v-else>{{ query.data.title }}</span>
277 * </li>
278 * </ul>
279 * </template>
280 * ```
281 * @example
282 * Combining results into a single value:
283 * ```vue
284 * <script setup lang="ts">
285 * import { useQueries } from '@tanstack/vue-query'
286 *
287 * const props = defineProps<{ ids: Array<number> }>()
288 *
289 * const combined = useQueries({
290 * queries: () =>
291 * props.ids.map((id) => ({
292 * queryKey: ['post', id],
293 * queryFn: () => fetchPost(id),
294 * })),
295 * combine: (postQueries) => ({
296 * data: postQueries.map((query) => query.data),
297 * isPending: postQueries.some((query) => query.isPending),
298 * isError: postQueries.some((query) => query.isError),
299 * }),
300 * })
301 * </script>
302 *
303 * <template>
304 * <span v-if="combined.isPending">Loading...</span>
305 * <span v-else-if="combined.isError">Error!</span>
306 * <ul v-else>
307 * <li v-for="post in combined.data" :key="post.id">{{ post.title }}</li>
308 * </ul>
309 * </template>
310 * ```
311 * @example
312 * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
313 * `select` inline still falls back to `unknown` β wrap the spread in `queryOptions` again so the override is
314 * resolved before it reaches `useQueries`:
315 * ```vue
316 * <script setup lang="ts">
317 * import { queryOptions, useQueries } from '@tanstack/vue-query'
318 *
319 * const props = defineProps<{ id: number }>()
320 *
321 * const postOptions = (id: number) =>
322 * queryOptions({
323 * queryKey: ['post', id],
324 * queryFn: () => fetchPost(id),
325 * })
326 *
327 * const [{ data: broken }] = useQueries({
328 * queries: () => [
329 * {
330 * ...postOptions(props.id),
331 * // β `data` is `unknown` here
332 * select: (data) => data.title,
333 * },
334 * ],
335 * })
336 *
337 * const [{ data: fixed }] = useQueries({
338 * queries: () => [
339 * queryOptions({
340 * ...postOptions(props.id),
341 * // β
`data` is `Post`
342 * select: (data) => data.title,
343 * }),
344 * ],
345 * })
346 * </script>
347 *
348 * <template>
349 * <h1>{{ fixed }}</h1>
350 * </template>
351 * ```
352 */
353export function useQueries<
354 T extends Array<any>,
355 TCombinedResult = UseQueriesResults<T>,
356>(
357 {
358 queries,
359 ...options
360 }: ShallowOption & {
361 queries:
362 | (() => MaybeRefDeep<UseQueriesOptionsArg<T>>)
363 | MaybeRefDeep<UseQueriesOptionsArg<T>>
364 | MaybeRefDeep<
365 readonly [
366 ...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> },
367 ]
368 >
369 combine?: (result: UseQueriesResults<T>) => TCombinedResult
370 },
371 queryClient?: QueryClient,
372): Readonly<Ref<TCombinedResult>> {
373 if (process.env.NODE_ENV === 'development') {
374 if (!getCurrentScope()) {
375 console.warn(
376 '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.',
377 )
378 }
379 }
380β
381 const client = queryClient || useQueryClient()
382β
383 const defaultedQueries = computed(() => {
384 const resolvedQueries =
385 typeof queries === 'function'
386 ? (queries as () => MaybeRefDeep<UseQueriesOptionsArg<T>>)()
387 : queries
388 // Only unref the top level array.
389 const queriesRaw = unref(resolvedQueries) as ReadonlyArray<any>
390β
391 // Unref the rest for each element in the top level array.
392 return queriesRaw.map((queryOptions) => {
393 const clonedOptions = cloneDeepUnref(queryOptions)
394β
395 // A zero-arg function is a Vue getter and must run here so its refs are tracked.
396 // `(query) => boolean` is query-core's callback and is left for core to call.
397 if (
398 typeof clonedOptions.enabled === 'function' &&
399 clonedOptions.enabled.length === 0
400 ) {
401 clonedOptions.enabled = clonedOptions.enabled()
402 }
403β
404 const defaulted = client.defaultQueryOptions(clonedOptions)
405 defaulted._optimisticResults = client.isRestoring?.value
406 ? 'isRestoring'
407 : 'optimistic'
408β
409 return defaulted
410 })
411 })
412β
413 const observer = new QueriesObserver<TCombinedResult>(
414 client,
415 defaultedQueries.value,
416 options as QueriesObserverOptions<TCombinedResult>,
417 )
418β
419 const getOptimisticResult = () => {
420 const [results, getCombinedResult] = observer.getOptimisticResult(
421 defaultedQueries.value,
422 (options as QueriesObserverOptions<TCombinedResult>).combine,
423 )
424β
425 return getCombinedResult(
426 results.map((result, index) => {
427 return {
428 ...result,
429 refetch: async (...args: Array<any>) => {
430 const [{ [index]: query }] = observer.getOptimisticResult(
431 defaultedQueries.value,
432 (options as QueriesObserverOptions<TCombinedResult>).combine,
433 )
434β
435 return query!.refetch(...args)
436 },
437 }
438 }),
439 )
440 }
441β
442 const state = shallowRef(getOptimisticResult())
443β
444 let unsubscribe = () => {
445 // noop
446 }
447β
448 if (client.isRestoring) {
449 watch(
450 client.isRestoring,
451 (isRestoring) => {
452 if (!isRestoring) {
453 unsubscribe()
454 unsubscribe = observer.subscribe(() => {
455 state.value = getOptimisticResult()
456 })
457β
458 state.value = getOptimisticResult()
459 }
460 },
461 { immediate: true },
462 )
463 }
464β
465 watch(defaultedQueries, (queriesValue) => {
466 observer.setQueries(
467 queriesValue,
468 options as QueriesObserverOptions<TCombinedResult>,
469 )
470 state.value = getOptimisticResult()
471 })
472β
473 onScopeDispose(() => {
474 unsubscribe()
475 })
476β
477 return options.shallow
478 ? shallowReadonly(state)
479 : (readonly(state) as Readonly<Ref<TCombinedResult>>)
480}