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