Open History to see the last commit
1'use client'
2import * as React from 'react'
3β
4import {
5 QueriesObserver,
6 QueryObserver,
7 noop,
8 notifyManager,
9} from '@tanstack/query-core'
10import { useQueryClient } from './QueryClientProvider'
11import { useIsRestoring } from './IsRestoringProvider'
12import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
13import {
14 ensurePreventErrorBoundaryRetry,
15 getHasError,
16 useClearResetErrorBoundary,
17} from './errorBoundaryUtils'
18import {
19 ensureSuspenseTimers,
20 fetchOptimistic,
21 shouldSuspend,
22} from './suspense'
23import type {
24 DefinedUseQueryResult,
25 UseQueryOptions,
26 UseQueryResult,
27} from './types'
28import type {
29 DefaultError,
30 OmitKeyof,
31 QueriesObserverOptions,
32 QueriesPlaceholderDataFunction,
33 QueryClient,
34 QueryFunction,
35 QueryKey,
36 QueryObserverOptions,
37 ThrowOnError,
38} from '@tanstack/query-core'
39β
40// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.
41// `placeholderData` function always gets undefined passed
42type UseQueryOptionsForUseQueries<
43 TQueryFnData = unknown,
44 TError = DefaultError,
45 TData = TQueryFnData,
46 TQueryKey extends QueryKey = QueryKey,
47> = OmitKeyof<
48 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
49 'placeholderData' | 'subscribed'
50> & {
51 placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>
52}
53β
54// Avoid TS depth-limit error in case of large array literal
55type MAXIMUM_DEPTH = 20
56β
57// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
58type SkipTokenForUseQueries = symbol
59β
60type GetUseQueryOptionsForUseQueries<T> =
61 // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
62 T extends {
63 queryFnData: infer TQueryFnData
64 error?: infer TError
65 data: infer TData
66 }
67 ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
68 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
69 ? UseQueryOptionsForUseQueries<TQueryFnData, TError>
70 : T extends { data: infer TData; error?: infer TError }
71 ? UseQueryOptionsForUseQueries<unknown, TError, TData>
72 : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]
73 T extends [infer TQueryFnData, infer TError, infer TData]
74 ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
75 : T extends [infer TQueryFnData, infer TError]
76 ? UseQueryOptionsForUseQueries<TQueryFnData, TError>
77 : T extends [infer TQueryFnData]
78 ? UseQueryOptionsForUseQueries<TQueryFnData>
79 : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided
80 T extends {
81 queryFn?:
82 | QueryFunction<infer TQueryFnData, infer TQueryKey>
83 | SkipTokenForUseQueries
84 select?: (data: any) => infer TData
85 throwOnError?: ThrowOnError<any, infer TError, any, any>
86 }
87 ? UseQueryOptionsForUseQueries<
88 TQueryFnData,
89 unknown extends TError ? DefaultError : TError,
90 unknown extends TData ? TQueryFnData : TData,
91 TQueryKey
92 >
93 : // Fallback
94 UseQueryOptionsForUseQueries
95β
96// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult
97type GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {
98 initialData?: infer TInitialData
99}
100 ? unknown extends TInitialData
101 ? UseQueryResult<TData, TError>
102 : TInitialData extends TData
103 ? DefinedUseQueryResult<TData, TError>
104 : TInitialData extends () => infer TInitialDataResult
105 ? unknown extends TInitialDataResult
106 ? UseQueryResult<TData, TError>
107 : TInitialDataResult extends TData
108 ? DefinedUseQueryResult<TData, TError>
109 : UseQueryResult<TData, TError>
110 : UseQueryResult<TData, TError>
111 : UseQueryResult<TData, TError>
112β
113type GetUseQueryResult<T> =
114 // Part 1: responsible for mapping explicit type parameter to function result, if object
115 T extends { queryFnData: any; error?: infer TError; data: infer TData }
116 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
117 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
118 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
119 : T extends { data: infer TData; error?: infer TError }
120 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
121 : // Part 2: responsible for mapping explicit type parameter to function result, if tuple
122 T extends [any, infer TError, infer TData]
123 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
124 : T extends [infer TQueryFnData, infer TError]
125 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
126 : T extends [infer TQueryFnData]
127 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>
128 : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided
129 T extends {
130 queryFn?:
131 | QueryFunction<infer TQueryFnData, any>
132 | SkipTokenForUseQueries
133 select?: (data: any) => infer TData
134 throwOnError?: ThrowOnError<any, infer TError, any, any>
135 }
136 ? GetDefinedOrUndefinedQueryResult<
137 T,
138 unknown extends TData ? TQueryFnData : TData,
139 unknown extends TError ? DefaultError : TError
140 >
141 : // Fallback
142 UseQueryResult
143β
144/**
145 * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's
146 * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements β past that, a tuple falls
147 * back to a single homogeneous options type.
148 *
149 * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally
150 * matches a query options object is mapped per-element instead, still inferring each entry individually; any
151 * other non-tuple array β one whose element type doesn't match the expected options shape β falls back to
152 * that same homogeneous options type too.
153 *
154 * @template T - The type of the `queries` array as written at the call site.
155 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
156 * to be set explicitly.
157 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
158 * meant to be set explicitly.
159 */
160export type QueriesOptions<
161 T extends Array<any>,
162 TResults extends Array<any> = [],
163 TDepth extends ReadonlyArray<number> = [],
164> = TDepth['length'] extends MAXIMUM_DEPTH
165 ? Array<UseQueryOptionsForUseQueries>
166 : T extends []
167 ? []
168 : T extends [infer Head]
169 ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]
170 : T extends [infer Head, ...infer Tails]
171 ? QueriesOptions<
172 [...Tails],
173 [...TResults, GetUseQueryOptionsForUseQueries<Head>],
174 [...TDepth, 1]
175 >
176 : ReadonlyArray<unknown> extends T
177 ? T
178 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
179 // use this to infer the param types in the case of Array.map() argument
180 T extends Array<
181 UseQueryOptionsForUseQueries<
182 infer TQueryFnData,
183 infer TError,
184 infer TData,
185 infer TQueryKey
186 >
187 >
188 ? Array<
189 UseQueryOptionsForUseQueries<
190 TQueryFnData,
191 TError,
192 TData,
193 TQueryKey
194 >
195 >
196 : // Fallback
197 Array<UseQueryOptionsForUseQueries>
198β
199/**
200 * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each
201 * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped
202 * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a
203 * single homogeneous {@link UseQueryResult} type.
204 *
205 * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.
206 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
207 * to be set explicitly.
208 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
209 * meant to be set explicitly.
210 */
211export type QueriesResults<
212 T extends Array<any>,
213 TResults extends Array<any> = [],
214 TDepth extends ReadonlyArray<number> = [],
215> = TDepth['length'] extends MAXIMUM_DEPTH
216 ? Array<UseQueryResult>
217 : T extends []
218 ? []
219 : T extends [infer Head]
220 ? [...TResults, GetUseQueryResult<Head>]
221 : T extends [infer Head, ...infer Tails]
222 ? QueriesResults<
223 [...Tails],
224 [...TResults, GetUseQueryResult<Head>],
225 [...TDepth, 1]
226 >
227 : { [K in keyof T]: GetUseQueryResult<T[K]> }
228β
229/**
230 * The `useQueries` hook can be used to fetch a variable number of queries.
231 *
232 * The `queries` key accepts an array with query option objects mostly identical to `useQuery` β the top-level
233 * `subscribed` option isn't accepted per query (see `placeholderData` below for another difference). A custom
234 * `QueryClient` is supplied once, as `useQueries`' own top-level second argument, rather than per query.
235 *
236 * Having the same query key more than once in the array of query objects may cause some data to be shared
237 * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
238 * structure.
239 *
240 * The `combine` option can be used to combine the results of the queries into a single value. The result will
241 * be structurally shared to be as referentially stable as possible.
242 *
243 * @remarks The `combine` function only re-runs if it changed referentially, or if any of the query results
244 * changed. An inlined `combine` function, as shown in the example below, therefore runs on every render β wrap
245 * it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to
246 * avoid that.
247 *
248 * Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling
249 * `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter
250 * of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls
251 * back to `unknown` β a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate
252 * the `select` parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in
253 * a single object _before_ it reaches `useQueries`, to work around this β see the example below. The same
254 * limitation applies to {@link useSuspenseQueries}.
255 *
256 * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
257 * previously rendered queries, because the number of queries can differ between renders.
258 * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
259 * will be used.
260 * @returns The combined result. Without `combine`, this is an array with all the query results, in the same
261 * order as the input. When `combine` is provided, this is the value returned by `combine` instead.
262 *
263 * @example
264 * ```tsx
265 * import { useQueries } from '@tanstack/react-query'
266 *
267 * function Posts({ ids }: { ids: Array<number> }) {
268 * const postQueries = useQueries({
269 * queries: ids.map((id) => ({
270 * queryKey: ['post', id],
271 * queryFn: () => fetchPost(id),
272 * staleTime: Infinity,
273 * })),
274 * })
275 *
276 * return (
277 * <ul>
278 * {postQueries.map((query, index) => {
279 * if (query.isPending) return <li key={ids[index]}>Loading...</li>
280 * if (query.isError) return <li key={ids[index]}>Error: {query.error.message}</li>
281 * return <li key={ids[index]}>{query.data.title}</li>
282 * })}
283 * </ul>
284 * )
285 * }
286 * ```
287 *
288 * @example
289 * Combining results into a single value:
290 * ```tsx
291 * import { useQueries } from '@tanstack/react-query'
292 *
293 * function Posts({ ids }: { ids: Array<number> }) {
294 * const { data, isPending, isError } = useQueries({
295 * queries: ids.map((id) => ({
296 * queryKey: ['post', id],
297 * queryFn: () => fetchPost(id),
298 * })),
299 * combine: (postQueries) => {
300 * return {
301 * data: postQueries.map((query) => query.data),
302 * isPending: postQueries.some((query) => query.isPending),
303 * isError: postQueries.some((query) => query.isError),
304 * }
305 * },
306 * })
307 *
308 * if (isPending) return 'Loading...'
309 * if (isError) return 'Error loading posts'
310 *
311 * return (
312 * <ul>
313 * {data.map((post) => (
314 * <li key={post?.id}>{post?.title}</li>
315 * ))}
316 * </ul>
317 * )
318 * }
319 * ```
320 *
321 * @example
322 * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
323 * `select` inline still falls back to `unknown` β wrap the spread in `queryOptions` again so the override is
324 * resolved before it reaches `useQueries`:
325 * ```tsx
326 * import { queryOptions, useQueries } from '@tanstack/react-query'
327 *
328 * const postOptions = (id: number) =>
329 * queryOptions({
330 * queryKey: ['post', id],
331 * queryFn: () => fetchPost(id),
332 * })
333 *
334 * function PostTitle({ id }: { id: number }) {
335 * const [{ data: broken }] = useQueries({
336 * queries: [
337 * {
338 * ...postOptions(id),
339 * // β `data` is `unknown` here
340 * select: (data) => data.title,
341 * },
342 * ],
343 * })
344 *
345 * const [{ data: fixed }] = useQueries({
346 * queries: [
347 * queryOptions({
348 * ...postOptions(id),
349 * // β
`data` is `Post`
350 * select: (data) => data.title,
351 * }),
352 * ],
353 * })
354 *
355 * return <h1>{fixed}</h1>
356 * }
357 * ```
358 */
359export function useQueries<
360 T extends Array<any>,
361 TCombinedResult = QueriesResults<T>,
362>(
363 {
364 queries,
365 ...options
366 }: {
367 /**
368 * An array with query option objects, mostly identical to `useQuery` β except that `queryClient` and
369 * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and
370 * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`
371 * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.
372 */
373 queries:
374 | readonly [...QueriesOptions<T>]
375 | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]
376 /**
377 * Use this to combine the results of the queries into a single value. The result will be structurally
378 * shared to be as referentially stable as possible.
379 */
380 combine?: (result: QueriesResults<T>) => TCombinedResult
381 /**
382 * Set this to `false` to unsubscribe this observer from updates to the query cache.
383 *
384 * @defaultValue true
385 */
386 subscribed?: boolean
387 },
388 queryClient?: QueryClient,
389): TCombinedResult {
390 const client = useQueryClient(queryClient)
391 const isRestoring = useIsRestoring()
392 const errorResetBoundary = useQueryErrorResetBoundary()
393 const subscribed = options.subscribed !== false
394β
395 const defaultedQueries = React.useMemo(
396 () =>
397 queries.map((opts) => {
398 const defaultedOptions = client.defaultQueryOptions(
399 opts as QueryObserverOptions,
400 )
401β
402 // Make sure the results are already in fetching state before subscribing or updating options
403 defaultedOptions._optimisticResults = isRestoring
404 ? 'isRestoring'
405 : subscribed
406 ? 'optimistic'
407 : undefined
408β
409 return defaultedOptions
410 }),
411 [queries, client, isRestoring, subscribed],
412 )
413β
414 defaultedQueries.forEach((queryOptions) => {
415 ensureSuspenseTimers(queryOptions)
416 const query = client.getQueryCache().get(queryOptions.queryHash)
417 ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)
418 })
419β
420 useClearResetErrorBoundary(errorResetBoundary)
421β
422 const [observer] = React.useState(
423 () =>
424 new QueriesObserver<TCombinedResult>(
425 client,
426 defaultedQueries,
427 options as QueriesObserverOptions<TCombinedResult>,
428 ),
429 )
430β
431 // note: this must be called before useSyncExternalStore
432 const [optimisticResult, getCombinedResult, trackResult] =
433 observer.getOptimisticResult(
434 defaultedQueries,
435 (options as QueriesObserverOptions<TCombinedResult>).combine,
436 )
437β
438 const shouldSubscribe = !isRestoring && subscribed
439 React.useSyncExternalStore(
440 React.useCallback(
441 (onStoreChange) =>
442 shouldSubscribe
443 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
444 : noop,
445 [observer, shouldSubscribe],
446 ),
447 () => observer.getCurrentResult(),
448 () => observer.getCurrentResult(),
449 )
450β
451 React.useEffect(() => {
452 observer.setQueries(
453 defaultedQueries,
454 options as QueriesObserverOptions<TCombinedResult>,
455 )
456 }, [defaultedQueries, options, observer])
457β
458 const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>
459 shouldSuspend(defaultedQueries[index], result),
460 )
461β
462 const suspensePromises = shouldAtLeastOneSuspend
463 ? optimisticResult.flatMap((result, index) => {
464 const opts = defaultedQueries[index]
465β
466 if (opts && shouldSuspend(opts, result)) {
467 const queryObserver = new QueryObserver(client, opts)
468 return fetchOptimistic(opts, queryObserver, errorResetBoundary)
469 }
470 return []
471 })
472 : []
473β
474 if (suspensePromises.length > 0) {
475 throw Promise.all(suspensePromises)
476 }
477 const firstSingleResultWhichShouldThrow = optimisticResult.find(
478 (result, index) => {
479 const query = defaultedQueries[index]
480 return (
481 query &&
482 getHasError({
483 result,
484 errorResetBoundary,
485 throwOnError: query.throwOnError,
486 query: client.getQueryCache().get(query.queryHash),
487 suspense: query.suspense,
488 })
489 )
490 },
491 )
492β
493 if (firstSingleResultWhichShouldThrow) {
494 throw firstSingleResultWhichShouldThrow.error
495 }
496β
497 return getCombinedResult(trackResult())
498}