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