Open History to see the last commit
1'use client'
2import { skipToken } from '@tanstack/query-core'
3import { useQueries } from './useQueries'
4import { defaultThrowOnError } from './suspense'
5import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types'
6import type {
7 DefaultError,
8 QueryClient,
9 QueryFunction,
10 ThrowOnError,
11} from '@tanstack/query-core'
12
13// Avoid TS depth-limit error in case of large array literal
14type MAXIMUM_DEPTH = 20
15
16// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
17type SkipTokenForUseQueries = symbol
18
19type GetUseSuspenseQueryOptions<T> =
20 // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
21 T extends {
22 queryFnData: infer TQueryFnData
23 error?: infer TError
24 data: infer TData
25 }
26 ? UseSuspenseQueryOptions<TQueryFnData, TError, TData>
27 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
28 ? UseSuspenseQueryOptions<TQueryFnData, TError>
29 : T extends { data: infer TData; error?: infer TError }
30 ? UseSuspenseQueryOptions<unknown, TError, TData>
31 : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]
32 T extends [infer TQueryFnData, infer TError, infer TData]
33 ? UseSuspenseQueryOptions<TQueryFnData, TError, TData>
34 : T extends [infer TQueryFnData, infer TError]
35 ? UseSuspenseQueryOptions<TQueryFnData, TError>
36 : T extends [infer TQueryFnData]
37 ? UseSuspenseQueryOptions<TQueryFnData>
38 : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided
39 T extends {
40 queryFn?:
41 | QueryFunction<infer TQueryFnData, infer TQueryKey>
42 | SkipTokenForUseQueries
43 select?: (data: any) => infer TData
44 throwOnError?: ThrowOnError<any, infer TError, any, any>
45 }
46 ? UseSuspenseQueryOptions<
47 TQueryFnData,
48 TError,
49 TData,
50 TQueryKey
51 >
52 : T extends {
53 queryFn?:
54 | QueryFunction<infer TQueryFnData, infer TQueryKey>
55 | SkipTokenForUseQueries
56 throwOnError?: ThrowOnError<any, infer TError, any, any>
57 }
58 ? UseSuspenseQueryOptions<
59 TQueryFnData,
60 TError,
61 TQueryFnData,
62 TQueryKey
63 >
64 : // Fallback
65 UseSuspenseQueryOptions
66
67type GetUseSuspenseQueryResult<T> =
68 // Part 1: responsible for mapping explicit type parameter to function result, if object
69 T extends { queryFnData: any; error?: infer TError; data: infer TData }
70 ? UseSuspenseQueryResult<TData, TError>
71 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
72 ? UseSuspenseQueryResult<TQueryFnData, TError>
73 : T extends { data: infer TData; error?: infer TError }
74 ? UseSuspenseQueryResult<TData, TError>
75 : // Part 2: responsible for mapping explicit type parameter to function result, if tuple
76 T extends [any, infer TError, infer TData]
77 ? UseSuspenseQueryResult<TData, TError>
78 : T extends [infer TQueryFnData, infer TError]
79 ? UseSuspenseQueryResult<TQueryFnData, TError>
80 : T extends [infer TQueryFnData]
81 ? UseSuspenseQueryResult<TQueryFnData>
82 : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided
83 T extends {
84 queryFn?:
85 | QueryFunction<infer TQueryFnData, any>
86 | SkipTokenForUseQueries
87 select?: (data: any) => infer TData
88 throwOnError?: ThrowOnError<any, infer TError, any, any>
89 }
90 ? UseSuspenseQueryResult<
91 unknown extends TData ? TQueryFnData : TData,
92 unknown extends TError ? DefaultError : TError
93 >
94 : T extends {
95 queryFn?:
96 | QueryFunction<infer TQueryFnData, any>
97 | SkipTokenForUseQueries
98 throwOnError?: ThrowOnError<any, infer TError, any, any>
99 }
100 ? UseSuspenseQueryResult<
101 TQueryFnData,
102 unknown extends TError ? DefaultError : TError
103 >
104 : // Fallback
105 UseSuspenseQueryResult
106
107/**
108 * The `queries` array accepted by `useSuspenseQueries`. Recursively unwraps each tuple element so every
109 * entry's `queryFn`/`select` are inferred individually, up to 20 elements — past that, a tuple falls back to
110 * a single homogeneous {@link UseSuspenseQueryOptions} type.
111 *
112 * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally
113 * matches a query options object is mapped per-element instead, still inferring each entry individually; any
114 * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to
115 * that same homogeneous options type too.
116 *
117 * @template T - The type of the `queries` array as written at the call site.
118 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
119 * to be set explicitly.
120 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
121 * meant to be set explicitly.
122 */
123export type SuspenseQueriesOptions<
124 T extends Array<any>,
125 TResults extends Array<any> = [],
126 TDepth extends ReadonlyArray<number> = [],
127> = TDepth['length'] extends MAXIMUM_DEPTH
128 ? Array<UseSuspenseQueryOptions>
129 : T extends []
130 ? []
131 : T extends [infer Head]
132 ? [...TResults, GetUseSuspenseQueryOptions<Head>]
133 : T extends [infer Head, ...infer Tails]
134 ? SuspenseQueriesOptions<
135 [...Tails],
136 [...TResults, GetUseSuspenseQueryOptions<Head>],
137 [...TDepth, 1]
138 >
139 : Array<unknown> extends T
140 ? T
141 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
142 // use this to infer the param types in the case of Array.map() argument
143 T extends Array<
144 UseSuspenseQueryOptions<
145 infer TQueryFnData,
146 infer TError,
147 infer TData,
148 infer TQueryKey
149 >
150 >
151 ? Array<
152 UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>
153 >
154 : // Fallback
155 Array<UseSuspenseQueryOptions>
156
157/**
158 * The result type returned by `useSuspenseQueries`, when no `combine` is provided. Mirrors
159 * {@link SuspenseQueriesOptions}: each tuple element's result type is inferred individually, up to 20 elements.
160 * A non-tuple array is mapped per-element instead, still inferring each entry individually; only past 20
161 * elements does this fall back to a single homogeneous {@link UseSuspenseQueryResult} type.
162 *
163 * @template T - The type of the `queries` array, as inferred by {@link SuspenseQueriesOptions}.
164 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
165 * to be set explicitly.
166 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
167 * meant to be set explicitly.
168 */
169export type SuspenseQueriesResults<
170 T extends Array<any>,
171 TResults extends Array<any> = [],
172 TDepth extends ReadonlyArray<number> = [],
173> = TDepth['length'] extends MAXIMUM_DEPTH
174 ? Array<UseSuspenseQueryResult>
175 : T extends []
176 ? []
177 : T extends [infer Head]
178 ? [...TResults, GetUseSuspenseQueryResult<Head>]
179 : T extends [infer Head, ...infer Tails]
180 ? SuspenseQueriesResults<
181 [...Tails],
182 [...TResults, GetUseSuspenseQueryResult<Head>],
183 [...TDepth, 1]
184 >
185 : { [K in keyof T]: GetUseSuspenseQueryResult<T[K]> }
186
187/**
188 * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed`
189 * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`.
190 *
191 * @param options - The `queries` array to run in Suspense, and an optional `combine` function.
192 * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
193 * will be used.
194 * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be
195 * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived
196 * flags set accordingly).
197 *
198 * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone
199 * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid
200 * this, make sure to set a high enough `staleTime`. Cancellation does not work.
201 *
202 * @example
203 * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
204 * required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
205 * Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
206 * ```tsx
207 * import { Suspense } from 'react'
208 * import { ErrorBoundary } from 'react-error-boundary'
209 * import {
210 * QueryErrorResetBoundary,
211 * useSuspenseQueries,
212 * } from '@tanstack/react-query'
213 *
214 * function Posts({ ids }: { ids: Array<number> }) {
215 * // Every result is guaranteed to be defined — no per-query `isPending` check needed.
216 * const postQueries = useSuspenseQueries({
217 * queries: ids.map((id) => ({
218 * queryKey: ['post', id],
219 * queryFn: () => fetchPost(id),
220 * })),
221 * })
222 *
223 * return (
224 * <ul>
225 * {postQueries.map((query) => (
226 * <li key={query.data.id}>{query.data.title}</li>
227 * ))}
228 * </ul>
229 * )
230 * }
231 *
232 * function App() {
233 * return (
234 * <QueryErrorResetBoundary>
235 * {({ reset }) => (
236 * <ErrorBoundary
237 * onReset={reset}
238 * fallbackRender={({ resetErrorBoundary }) => (
239 * <div>
240 * There was an error!
241 * <button onClick={() => resetErrorBoundary()}>Try again</button>
242 * </div>
243 * )}
244 * >
245 * <Suspense fallback={<h1>Loading posts...</h1>}>
246 * <Posts ids={[1, 2, 3]} />
247 * </Suspense>
248 * </ErrorBoundary>
249 * )}
250 * </QueryErrorResetBoundary>
251 * )
252 * }
253 * ```
254 *
255 * @example
256 * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so
257 * they fetch in parallel rather than suspending one after another:
258 * ```tsx
259 * import { Suspense } from 'react'
260 * import { ErrorBoundary } from 'react-error-boundary'
261 * import {
262 * QueryErrorResetBoundary,
263 * useSuspenseQueries,
264 * } from '@tanstack/react-query'
265 *
266 * function Dashboard() {
267 * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({
268 * queries: [
269 * { queryKey: ['users'], queryFn: fetchUsers },
270 * { queryKey: ['teams'], queryFn: fetchTeams },
271 * { queryKey: ['projects'], queryFn: fetchProjects },
272 * ],
273 * })
274 *
275 * return (
276 * <div>
277 * <UserList users={usersQuery.data} />
278 * <TeamList teams={teamsQuery.data} />
279 * <ProjectList projects={projectsQuery.data} />
280 * </div>
281 * )
282 * }
283 *
284 * function App() {
285 * return (
286 * <QueryErrorResetBoundary>
287 * {({ reset }) => (
288 * <ErrorBoundary
289 * onReset={reset}
290 * fallbackRender={({ resetErrorBoundary }) => (
291 * <div>
292 * There was an error!
293 * <button onClick={() => resetErrorBoundary()}>Try again</button>
294 * </div>
295 * )}
296 * >
297 * <Suspense fallback={<h1>Loading dashboard...</h1>}>
298 * <Dashboard />
299 * </Suspense>
300 * </ErrorBoundary>
301 * )}
302 * </QueryErrorResetBoundary>
303 * )
304 * }
305 * ```
306 *
307 * @example
308 * `combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes,
309 * not on every individual query update. This overload is the only one that accepts `combine`:
310 * ```tsx
311 * import { Suspense } from 'react'
312 * import { ErrorBoundary } from 'react-error-boundary'
313 * import {
314 * QueryErrorResetBoundary,
315 * useSuspenseQueries,
316 * } from '@tanstack/react-query'
317 *
318 * function Refresh() {
319 * const anyFetching = useSuspenseQueries({
320 * queries: [
321 * { queryKey: ['users'], queryFn: fetchUsers },
322 * { queryKey: ['teams'], queryFn: fetchTeams },
323 * ],
324 * combine: (results) => results.some((result) => result.isFetching),
325 * })
326 *
327 * return anyFetching ? <span>Refreshing…</span> : null
328 * }
329 *
330 * function App() {
331 * return (
332 * <QueryErrorResetBoundary>
333 * {({ reset }) => (
334 * <ErrorBoundary
335 * onReset={reset}
336 * fallbackRender={({ resetErrorBoundary }) => (
337 * <div>
338 * There was an error!
339 * <button onClick={() => resetErrorBoundary()}>Try again</button>
340 * </div>
341 * )}
342 * >
343 * <Suspense fallback={<h1>Loading dashboard...</h1>}>
344 * <Refresh />
345 * </Suspense>
346 * </ErrorBoundary>
347 * )}
348 * </QueryErrorResetBoundary>
349 * )
350 * }
351 * ```
352 */
353export function useSuspenseQueries<
354 T extends Array<any>,
355 TCombinedResult = SuspenseQueriesResults<T>,
356>(
357 options: {
358 /**
359 * An array with query option objects identical to `useSuspenseQuery`.
360 */
361 queries:
362 | readonly [...SuspenseQueriesOptions<T>]
363 | readonly [...{ [K in keyof T]: GetUseSuspenseQueryOptions<T[K]> }]
364 /**
365 * Use this to combine the results of the queries into a single value. The result will be structurally
366 * shared to be as referentially stable as possible.
367 */
368 combine?: (result: SuspenseQueriesResults<T>) => TCombinedResult
369 },
370 queryClient?: QueryClient,
371): TCombinedResult
372
373/**
374 * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed`
375 * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`.
376 *
377 * @param options - The `queries` array to run in Suspense, and an optional `combine` function.
378 * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
379 * will be used.
380 * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be
381 * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived
382 * flags set accordingly).
383 *
384 * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone
385 * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid
386 * this, make sure to set a high enough `staleTime`. Cancellation does not work.
387 *
388 * @example
389 * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
390 * required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
391 * Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
392 * ```tsx
393 * import { Suspense } from 'react'
394 * import { ErrorBoundary } from 'react-error-boundary'
395 * import {
396 * QueryErrorResetBoundary,
397 * useSuspenseQueries,
398 * } from '@tanstack/react-query'
399 *
400 * function Posts({ ids }: { ids: Array<number> }) {
401 * // Every result is guaranteed to be defined — no per-query `isPending` check needed.
402 * const postQueries = useSuspenseQueries({
403 * queries: ids.map((id) => ({
404 * queryKey: ['post', id],
405 * queryFn: () => fetchPost(id),
406 * })),
407 * })
408 *
409 * return (
410 * <ul>
411 * {postQueries.map((query) => (
412 * <li key={query.data.id}>{query.data.title}</li>
413 * ))}
414 * </ul>
415 * )
416 * }
417 *
418 * function App() {
419 * return (
420 * <QueryErrorResetBoundary>
421 * {({ reset }) => (
422 * <ErrorBoundary
423 * onReset={reset}
424 * fallbackRender={({ resetErrorBoundary }) => (
425 * <div>
426 * There was an error!
427 * <button onClick={() => resetErrorBoundary()}>Try again</button>
428 * </div>
429 * )}
430 * >
431 * <Suspense fallback={<h1>Loading posts...</h1>}>
432 * <Posts ids={[1, 2, 3]} />
433 * </Suspense>
434 * </ErrorBoundary>
435 * )}
436 * </QueryErrorResetBoundary>
437 * )
438 * }
439 * ```
440 *
441 * @example
442 * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so
443 * they fetch in parallel rather than suspending one after another:
444 * ```tsx
445 * import { Suspense } from 'react'
446 * import { ErrorBoundary } from 'react-error-boundary'
447 * import {
448 * QueryErrorResetBoundary,
449 * useSuspenseQueries,
450 * } from '@tanstack/react-query'
451 *
452 * function Dashboard() {
453 * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({
454 * queries: [
455 * { queryKey: ['users'], queryFn: fetchUsers },
456 * { queryKey: ['teams'], queryFn: fetchTeams },
457 * { queryKey: ['projects'], queryFn: fetchProjects },
458 * ],
459 * })
460 *
461 * return (
462 * <div>
463 * <UserList users={usersQuery.data} />
464 * <TeamList teams={teamsQuery.data} />
465 * <ProjectList projects={projectsQuery.data} />
466 * </div>
467 * )
468 * }
469 *
470 * function App() {
471 * return (
472 * <QueryErrorResetBoundary>
473 * {({ reset }) => (
474 * <ErrorBoundary
475 * onReset={reset}
476 * fallbackRender={({ resetErrorBoundary }) => (
477 * <div>
478 * There was an error!
479 * <button onClick={() => resetErrorBoundary()}>Try again</button>
480 * </div>
481 * )}
482 * >
483 * <Suspense fallback={<h1>Loading dashboard...</h1>}>
484 * <Dashboard />
485 * </Suspense>
486 * </ErrorBoundary>
487 * )}
488 * </QueryErrorResetBoundary>
489 * )
490 * }
491 * ```
492 */
493export function useSuspenseQueries<
494 T extends Array<any>,
495 TCombinedResult = SuspenseQueriesResults<T>,
496>(
497 options: {
498 /**
499 * An array with query option objects identical to `useSuspenseQuery`.
500 */
501 queries: readonly [...SuspenseQueriesOptions<T>]
502 /**
503 * Use this to combine the results of the queries into a single value. The result will be structurally
504 * shared to be as referentially stable as possible.
505 */
506 combine?: (result: SuspenseQueriesResults<T>) => TCombinedResult
507 },
508 queryClient?: QueryClient,
509): TCombinedResult
510
511export function useSuspenseQueries(options: any, queryClient?: QueryClient) {
512 return useQueries(
513 {
514 ...options,
515 queries: options.queries.map((query: any) => {
516 if (process.env.NODE_ENV !== 'production') {
517 if (query.queryFn === skipToken) {
518 console.error('skipToken is not allowed for useSuspenseQueries')
519 }
520 }
521
522 return {
523 ...query,
524 suspense: true,
525 throwOnError: defaultThrowOnError,
526 enabled: true,
527 placeholderData: undefined,
528 }
529 }),
530 },
531 queryClient,
532 )
533}