Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useQueries.ts

521 lines18.8 KB

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