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 * @param options - The `queries` array to run, and the optional `combine` and `shallow` options.
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 * @example
256 * ```vue
257 * <script setup lang="ts">
258 * import { useQueries } from '@tanstack/vue-query'
259 *
260 * const props = defineProps<{ ids: Array<number> }>()
261 *
262 * const postQueries = useQueries({
263 * queries: () =>
264 * props.ids.map((id) => ({
265 * queryKey: ['post', id],
266 * queryFn: () => fetchPost(id),
267 * staleTime: Infinity,
268 * })),
269 * })
270 * </script>
271 *
272 * <template>
273 * <ul>
274 * <li v-for="(query, index) in postQueries" :key="props.ids[index]">
275 * <span v-if="query.isPending">Loading...</span>
276 * <span v-else-if="query.isError">Error: {{ query.error.message }}</span>
277 * <span v-else>{{ query.data.title }}</span>
278 * </li>
279 * </ul>
280 * </template>
281 * ```
282 * @example
283 * Combining results into a single value:
284 * ```vue
285 * <script setup lang="ts">
286 * import { useQueries } from '@tanstack/vue-query'
287 *
288 * const props = defineProps<{ ids: Array<number> }>()
289 *
290 * const combined = useQueries({
291 * queries: () =>
292 * props.ids.map((id) => ({
293 * queryKey: ['post', id],
294 * queryFn: () => fetchPost(id),
295 * })),
296 * combine: (postQueries) => ({
297 * data: postQueries.map((query) => query.data),
298 * isPending: postQueries.some((query) => query.isPending),
299 * isError: postQueries.some((query) => query.isError),
300 * }),
301 * })
302 * </script>
303 *
304 * <template>
305 * <span v-if="combined.isPending">Loading...</span>
306 * <span v-else-if="combined.isError">Error!</span>
307 * <ul v-else>
308 * <li v-for="post in combined.data" :key="post.id">{{ post.title }}</li>
309 * </ul>
310 * </template>
311 * ```
312 * @example
313 * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
314 * `select` inline still falls back to `unknown` β wrap the spread in `queryOptions` again so the override is
315 * resolved before it reaches `useQueries`:
316 * ```vue
317 * <script setup lang="ts">
318 * import { queryOptions, useQueries } from '@tanstack/vue-query'
319 *
320 * const props = defineProps<{ id: number }>()
321 *
322 * const postOptions = (id: number) =>
323 * queryOptions({
324 * queryKey: ['post', id],
325 * queryFn: () => fetchPost(id),
326 * })
327 *
328 * const [{ data: broken }] = useQueries({
329 * queries: () => [
330 * {
331 * ...postOptions(props.id),
332 * // β `data` is `unknown` here
333 * select: (data) => data.title,
334 * },
335 * ],
336 * })
337 *
338 * const [{ data: fixed }] = useQueries({
339 * queries: () => [
340 * queryOptions({
341 * ...postOptions(props.id),
342 * // β
`data` is `Post`
343 * select: (data) => data.title,
344 * }),
345 * ],
346 * })
347 * </script>
348 *
349 * <template>
350 * <h1>{{ fixed }}</h1>
351 * </template>
352 * ```
353 */
354export function useQueries<
355 T extends Array<any>,
356 TCombinedResult = UseQueriesResults<T>,
357>(
358 {
359 queries,
360 ...options
361 }: ShallowOption & {
362 queries:
363 | (() => MaybeRefDeep<UseQueriesOptionsArg<T>>)
364 | MaybeRefDeep<UseQueriesOptionsArg<T>>
365 | MaybeRefDeep<
366 readonly [
367 ...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> },
368 ]
369 >
370 combine?: (result: UseQueriesResults<T>) => TCombinedResult
371 },
372 queryClient?: QueryClient,
373): Readonly<Ref<TCombinedResult>> {
374 if (process.env.NODE_ENV === 'development') {
375 if (!getCurrentScope()) {
376 console.warn(
377 '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.',
378 )
379 }
380 }
381β
382 const client = queryClient || useQueryClient()
383β
384 const defaultedQueries = computed(() => {
385 const resolvedQueries =
386 typeof queries === 'function'
387 ? (queries as () => MaybeRefDeep<UseQueriesOptionsArg<T>>)()
388 : queries
389 // Only unref the top level array.
390 const queriesRaw = unref(resolvedQueries) as ReadonlyArray<any>
391β
392 // Unref the rest for each element in the top level array.
393 return queriesRaw.map((queryOptions) => {
394 const clonedOptions = cloneDeepUnref(queryOptions)
395β
396 if (typeof clonedOptions.enabled === 'function') {
397 clonedOptions.enabled = queryOptions.enabled()
398 }
399β
400 const defaulted = client.defaultQueryOptions(clonedOptions)
401 defaulted._optimisticResults = client.isRestoring?.value
402 ? 'isRestoring'
403 : 'optimistic'
404β
405 return defaulted
406 })
407 })
408β
409 const observer = new QueriesObserver<TCombinedResult>(
410 client,
411 defaultedQueries.value,
412 options as QueriesObserverOptions<TCombinedResult>,
413 )
414β
415 const getOptimisticResult = () => {
416 const [results, getCombinedResult] = observer.getOptimisticResult(
417 defaultedQueries.value,
418 (options as QueriesObserverOptions<TCombinedResult>).combine,
419 )
420β
421 return getCombinedResult(
422 results.map((result, index) => {
423 return {
424 ...result,
425 refetch: async (...args: Array<any>) => {
426 const [{ [index]: query }] = observer.getOptimisticResult(
427 defaultedQueries.value,
428 (options as QueriesObserverOptions<TCombinedResult>).combine,
429 )
430β
431 return query!.refetch(...args)
432 },
433 }
434 }),
435 )
436 }
437β
438 const state = shallowRef(getOptimisticResult())
439β
440 let unsubscribe = () => {
441 // noop
442 }
443β
444 if (client.isRestoring) {
445 watch(
446 client.isRestoring,
447 (isRestoring) => {
448 if (!isRestoring) {
449 unsubscribe()
450 unsubscribe = observer.subscribe(() => {
451 state.value = getOptimisticResult()
452 })
453β
454 state.value = getOptimisticResult()
455 }
456 },
457 { immediate: true },
458 )
459 }
460β
461 watch(defaultedQueries, (queriesValue) => {
462 observer.setQueries(
463 queriesValue,
464 options as QueriesObserverOptions<TCombinedResult>,
465 )
466 state.value = getOptimisticResult()
467 })
468β
469 onScopeDispose(() => {
470 unsubscribe()
471 })
472β
473 return options.shallow
474 ? shallowReadonly(state)
475 : (readonly(state) as Readonly<Ref<TCombinedResult>>)
476}