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