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