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

useQueries.ts

494 lines18.2 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 element so every entry's
146 * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g.
147 * `unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls
148 * back to a single homogeneous options type.
149 *
150 * @template T - The type of the `queries` array as written at the call site.
151 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
152 * to be set explicitly.
153 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
154 * meant to be set explicitly.
155 */
156export type QueriesOptions<
157 T extends Array<any>,
158 TResults extends Array<any> = [],
159 TDepth extends ReadonlyArray<number> = [],
160> = TDepth['length'] extends MAXIMUM_DEPTH
161 ? Array<UseQueryOptionsForUseQueries>
162 : T extends []
163 ? []
164 : T extends [infer Head]
165 ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]
166 : T extends [infer Head, ...infer Tails]
167 ? QueriesOptions<
168 [...Tails],
169 [...TResults, GetUseQueryOptionsForUseQueries<Head>],
170 [...TDepth, 1]
171 >
172 : ReadonlyArray<unknown> extends T
173 ? T
174 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
175 // use this to infer the param types in the case of Array.map() argument
176 T extends Array<
177 UseQueryOptionsForUseQueries<
178 infer TQueryFnData,
179 infer TError,
180 infer TData,
181 infer TQueryKey
182 >
183 >
184 ? Array<
185 UseQueryOptionsForUseQueries<
186 TQueryFnData,
187 TError,
188 TData,
189 TQueryKey
190 >
191 >
192 : // Fallback
193 Array<UseQueryOptionsForUseQueries>
194​
195/**
196 * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each
197 * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped
198 * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a
199 * single homogeneous {@link UseQueryResult} type.
200 *
201 * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.
202 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
203 * to be set explicitly.
204 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
205 * meant to be set explicitly.
206 */
207export type QueriesResults<
208 T extends Array<any>,
209 TResults extends Array<any> = [],
210 TDepth extends ReadonlyArray<number> = [],
211> = TDepth['length'] extends MAXIMUM_DEPTH
212 ? Array<UseQueryResult>
213 : T extends []
214 ? []
215 : T extends [infer Head]
216 ? [...TResults, GetUseQueryResult<Head>]
217 : T extends [infer Head, ...infer Tails]
218 ? QueriesResults<
219 [...Tails],
220 [...TResults, GetUseQueryResult<Head>],
221 [...TDepth, 1]
222 >
223 : { [K in keyof T]: GetUseQueryResult<T[K]> }
224​
225/**
226 * The `useQueries` hook can be used to fetch a variable number of queries.
227 *
228 * The `queries` key accepts an array with query option objects mostly identical to `useQuery` β€” the top-level
229 * `subscribed` option isn't accepted per query (see `placeholderData` below for another difference). A custom
230 * `QueryClient` is supplied once, as `useQueries`' own top-level second argument, rather than per query.
231 *
232 * Having the same query key more than once in the array of query objects may cause some data to be shared
233 * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
234 * structure.
235 *
236 * The `combine` option can be used to combine the results of the queries into a single value. The result will
237 * be structurally shared to be as referentially stable as possible.
238 *
239 * @remarks The `combine` function only re-runs if it changed referentially, or if any of the query results
240 * changed. An inlined `combine` function, as shown in the example below, therefore runs on every render β€” wrap
241 * it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to
242 * avoid that.
243 *
244 * Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling
245 * `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter
246 * of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls
247 * back to `unknown` β€” a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate
248 * the `select` parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in
249 * a single object _before_ it reaches `useQueries`, to work around this β€” see the example below. The same
250 * limitation applies to {@link useSuspenseQueries}.
251 *
252 * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
253 * previously rendered queries, because the number of queries can differ between renders.
254 * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
255 * will be used.
256 * @returns The combined result. Without `combine`, this is an array with all the query results, in the same
257 * order as the input. When `combine` is provided, this is the value returned by `combine` instead.
258 *
259 * @example
260 * ```tsx
261 * import { useQueries } from '@tanstack/react-query'
262 *
263 * function Posts({ ids }: { ids: Array<number> }) {
264 * const postQueries = useQueries({
265 * queries: ids.map((id) => ({
266 * queryKey: ['post', id],
267 * queryFn: () => fetchPost(id),
268 * staleTime: Infinity,
269 * })),
270 * })
271 *
272 * return (
273 * <ul>
274 * {postQueries.map((query, index) => {
275 * if (query.isPending) return <li key={ids[index]}>Loading...</li>
276 * if (query.isError) return <li key={ids[index]}>Error: {query.error.message}</li>
277 * return <li key={ids[index]}>{query.data.title}</li>
278 * })}
279 * </ul>
280 * )
281 * }
282 * ```
283 *
284 * @example
285 * Combining results into a single value:
286 * ```tsx
287 * import { useQueries } from '@tanstack/react-query'
288 *
289 * function Posts({ ids }: { ids: Array<number> }) {
290 * const { data, isPending, isError } = useQueries({
291 * queries: ids.map((id) => ({
292 * queryKey: ['post', id],
293 * queryFn: () => fetchPost(id),
294 * })),
295 * combine: (postQueries) => {
296 * return {
297 * data: postQueries.map((query) => query.data),
298 * isPending: postQueries.some((query) => query.isPending),
299 * isError: postQueries.some((query) => query.isError),
300 * }
301 * },
302 * })
303 *
304 * if (isPending) return 'Loading...'
305 * if (isError) return 'Error loading posts'
306 *
307 * return (
308 * <ul>
309 * {data.map((post) => (
310 * <li key={post?.id}>{post?.title}</li>
311 * ))}
312 * </ul>
313 * )
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 *
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 const shouldSubscribe = !isRestoring && subscribed
435 React.useSyncExternalStore(
436 React.useCallback(
437 (onStoreChange) =>
438 shouldSubscribe
439 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
440 : noop,
441 [observer, shouldSubscribe],
442 ),
443 () => observer.getCurrentResult(),
444 () => observer.getCurrentResult(),
445 )
446​
447 React.useEffect(() => {
448 observer.setQueries(
449 defaultedQueries,
450 options as QueriesObserverOptions<TCombinedResult>,
451 )
452 }, [defaultedQueries, options, observer])
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())