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