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 * @template T - The type of the `queries` array as written at the call site.
154 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
155 * to be set explicitly.
156 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
157 * meant to be set explicitly.
158 */
159export type QueriesOptions<
160 T extends Array<any>,
161 TResults extends Array<any> = [],
162 TDepth extends ReadonlyArray<number> = [],
163> = TDepth['length'] extends MAXIMUM_DEPTH
164 ? Array<UseQueryOptionsForUseQueries>
165 : T extends []
166 ? []
167 : T extends [infer Head]
168 ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]
169 : T extends [infer Head, ...infer Tails]
170 ? QueriesOptions<
171 [...Tails],
172 [...TResults, GetUseQueryOptionsForUseQueries<Head>],
173 [...TDepth, 1]
174 >
175 : ReadonlyArray<unknown> extends T
176 ? T
177 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
178 // use this to infer the param types in the case of Array.map() argument
179 T extends Array<
180 UseQueryOptionsForUseQueries<
181 infer TQueryFnData,
182 infer TError,
183 infer TData,
184 infer TQueryKey
185 >
186 >
187 ? Array<
188 UseQueryOptionsForUseQueries<
189 TQueryFnData,
190 TError,
191 TData,
192 TQueryKey
193 >
194 >
195 : // Fallback
196 Array<UseQueryOptionsForUseQueries>
197β
198/**
199 * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each
200 * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped
201 * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a
202 * single homogeneous {@link UseQueryResult} type.
203 * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.
204 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
205 * to be set explicitly.
206 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
207 * meant to be set explicitly.
208 */
209export type QueriesResults<
210 T extends Array<any>,
211 TResults extends Array<any> = [],
212 TDepth extends ReadonlyArray<number> = [],
213> = TDepth['length'] extends MAXIMUM_DEPTH
214 ? Array<UseQueryResult>
215 : T extends []
216 ? []
217 : T extends [infer Head]
218 ? [...TResults, GetUseQueryResult<Head>]
219 : T extends [infer Head, ...infer Tails]
220 ? QueriesResults<
221 [...Tails],
222 [...TResults, GetUseQueryResult<Head>],
223 [...TDepth, 1]
224 >
225 : { [K in keyof T]: GetUseQueryResult<T[K]> }
226β
227/**
228 * The `useQueries` hook can be used to fetch a variable number of queries.
229 *
230 * The `queries` key accepts an array with query option objects mostly identical to `useQuery` β the top-level
231 * `subscribed` option isn't accepted per query (see `placeholderData` below for another difference). A custom
232 * `QueryClient` is supplied once, as `useQueries`' own top-level second argument, rather than per query.
233 *
234 * Having the same query key more than once in the array of query objects may cause some data to be shared
235 * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
236 * structure.
237 *
238 * The `combine` option can be used to combine the results of the queries into a single value. The result will
239 * be structurally shared to be as referentially stable as possible.
240 * @param options - The `queries` array to run, and the optional `combine` and `subscribed` options.
241 * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
242 * will be used.
243 * @returns The combined result. Without `combine`, this is an array with all the query results, in the same
244 * order as the input. When `combine` is provided, this is the value returned by `combine` instead.
245 * @throws {Error} The error of the first query that should be thrown to the nearest error boundary (see
246 * `throwOnError`). While suspending, it throws a promise instead.
247 * @remarks The `combine` function only re-runs if it changed referentially, or if any of the query results
248 * changed. An inlined `combine` function, as shown in the example below, therefore runs on every render β wrap
249 * it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to
250 * avoid that.
251 *
252 * Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling
253 * `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter
254 * of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls
255 * back to `unknown` β a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate
256 * the `select` parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in
257 * a single object _before_ it reaches `useQueries`, to work around this β see the example below. The same
258 * limitation applies to {@link useSuspenseQueries}.
259 *
260 * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
261 * previously rendered queries, because the number of queries can differ between renders.
262 * @example
263 * ```tsx
264 * import { useQueries } from '@tanstack/react-query'
265 *
266 * function Posts({ ids }: { ids: Array<number> }) {
267 * const postQueries = useQueries({
268 * queries: ids.map((id) => ({
269 * queryKey: ['post', id],
270 * queryFn: () => fetchPost(id),
271 * staleTime: Infinity,
272 * })),
273 * })
274 *
275 * return (
276 * <ul>
277 * {postQueries.map((query, index) => {
278 * if (query.isPending) return <li key={ids[index]}>Loading...</li>
279 * if (query.isError) return <li key={ids[index]}>Error: {query.error.message}</li>
280 * return <li key={ids[index]}>{query.data.title}</li>
281 * })}
282 * </ul>
283 * )
284 * }
285 * ```
286 * @example
287 * Combining results into a single value:
288 * ```tsx
289 * import { useQueries } from '@tanstack/react-query'
290 *
291 * function Posts({ ids }: { ids: Array<number> }) {
292 * const { data, isPending, isError } = useQueries({
293 * queries: ids.map((id) => ({
294 * queryKey: ['post', id],
295 * queryFn: () => fetchPost(id),
296 * })),
297 * combine: (postQueries) => {
298 * return {
299 * data: postQueries.map((query) => query.data),
300 * isPending: postQueries.some((query) => query.isPending),
301 * isError: postQueries.some((query) => query.isError),
302 * }
303 * },
304 * })
305 *
306 * if (isPending) return 'Loading...'
307 * if (isError) return 'Error loading posts'
308 *
309 * return (
310 * <ul>
311 * {data.map((post) => (
312 * <li key={post?.id}>{post?.title}</li>
313 * ))}
314 * </ul>
315 * )
316 * }
317 * ```
318 * @example
319 * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
320 * `select` inline still falls back to `unknown` β wrap the spread in `queryOptions` again so the override is
321 * resolved before it reaches `useQueries`:
322 * ```tsx
323 * import { queryOptions, useQueries } from '@tanstack/react-query'
324 *
325 * const postOptions = (id: number) =>
326 * queryOptions({
327 * queryKey: ['post', id],
328 * queryFn: () => fetchPost(id),
329 * })
330 *
331 * function PostTitle({ id }: { id: number }) {
332 * const [{ data: broken }] = useQueries({
333 * queries: [
334 * {
335 * ...postOptions(id),
336 * // β `data` is `unknown` here
337 * select: (data) => data.title,
338 * },
339 * ],
340 * })
341 *
342 * const [{ data: fixed }] = useQueries({
343 * queries: [
344 * queryOptions({
345 * ...postOptions(id),
346 * // β
`data` is `Post`
347 * select: (data) => data.title,
348 * }),
349 * ],
350 * })
351 *
352 * return <h1>{fixed}</h1>
353 * }
354 * ```
355 */
356export function useQueries<
357 T extends Array<any>,
358 TCombinedResult = QueriesResults<T>,
359>(
360 {
361 queries,
362 ...options
363 }: {
364 /**
365 * An array with query option objects, mostly identical to `useQuery` β except that `queryClient` and
366 * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and
367 * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`
368 * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.
369 */
370 queries:
371 | readonly [...QueriesOptions<T>]
372 | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]
373 /**
374 * Use this to combine the results of the queries into a single value. The result will be structurally
375 * shared to be as referentially stable as possible.
376 */
377 combine?: (result: QueriesResults<T>) => TCombinedResult
378 /**
379 * Set this to `false` to unsubscribe this observer from updates to the query cache.
380 * @defaultValue true
381 */
382 subscribed?: boolean
383 },
384 queryClient?: QueryClient,
385): TCombinedResult {
386 const client = useQueryClient(queryClient)
387 const isRestoring = useIsRestoring()
388 const errorResetBoundary = useQueryErrorResetBoundary()
389 const subscribed = options.subscribed !== false
390β
391 const defaultedQueries = React.useMemo(
392 () =>
393 queries.map((opts) => {
394 const defaultedOptions = client.defaultQueryOptions(
395 opts as QueryObserverOptions,
396 )
397β
398 // Make sure the results are already in fetching state before subscribing or updating options
399 defaultedOptions._optimisticResults = isRestoring
400 ? 'isRestoring'
401 : subscribed
402 ? 'optimistic'
403 : undefined
404β
405 return defaultedOptions
406 }),
407 [queries, client, isRestoring, subscribed],
408 )
409β
410 defaultedQueries.forEach((queryOptions) => {
411 ensureSuspenseTimers(queryOptions)
412 const query = client.getQueryCache().get(queryOptions.queryHash)
413 ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)
414 })
415β
416 useClearResetErrorBoundary(errorResetBoundary)
417β
418 const [observer] = React.useState(
419 () =>
420 new QueriesObserver<TCombinedResult>(
421 client,
422 defaultedQueries,
423 options as QueriesObserverOptions<TCombinedResult>,
424 ),
425 )
426β
427 // note: this must be called before useSyncExternalStore
428 const [optimisticResult, getCombinedResult, trackResult] =
429 observer.getOptimisticResult(
430 defaultedQueries,
431 (options as QueriesObserverOptions<TCombinedResult>).combine,
432 )
433β
434 React.useEffect(() => {
435 observer.setQueries(
436 defaultedQueries,
437 options as QueriesObserverOptions<TCombinedResult>,
438 )
439 }, [defaultedQueries, options, observer])
440β
441 const shouldSubscribe = !isRestoring && subscribed
442 React.useSyncExternalStore(
443 React.useCallback(
444 (onStoreChange) =>
445 shouldSubscribe
446 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
447 : noop,
448 [observer, shouldSubscribe],
449 ),
450 () => observer.getCurrentResult(),
451 () => observer.getCurrentResult(),
452 )
453β
454 const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>
455 shouldSuspend(defaultedQueries[index], result),
456 )
457β
458 const suspensePromises = shouldAtLeastOneSuspend
459 ? optimisticResult.flatMap((result, index) => {
460 const opts = defaultedQueries[index]
461β
462 if (opts && shouldSuspend(opts, result)) {
463 const queryObserver = new QueryObserver(client, opts)
464 return fetchOptimistic(opts, queryObserver, errorResetBoundary)
465 }
466 return []
467 })
468 : []
469β
470 if (suspensePromises.length > 0) {
471 throw Promise.all(suspensePromises)
472 }
473 const firstSingleResultWhichShouldThrow = optimisticResult.find(
474 (result, index) => {
475 const query = defaultedQueries[index]
476 return (
477 query &&
478 getHasError({
479 result,
480 errorResetBoundary,
481 throwOnError: query.throwOnError,
482 query: client.getQueryCache().get(query.queryHash),
483 suspense: query.suspense,
484 })
485 )
486 },
487 )
488β
489 if (firstSingleResultWhichShouldThrow) {
490 throw firstSingleResultWhichShouldThrow.error
491 }
492β
493 return getCombinedResult(trackResult())
494}