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

useQueries.ts

493 lines18.7 KB

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