Open History to see the last commit
1import { skipToken } from '@tanstack/query-core'
2import type {
3 DefaultError,
4 QueryClient,
5 QueryFunction,
6 ThrowOnError,
7} from '@tanstack/query-core'
8
9import { defaultThrowOnError } from './suspense'
10import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types'
11import { useQueries } from './useQueries'
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 'preact/compat'
208 * import { useErrorBoundary } from 'preact/hooks'
209 * import {
210 * QueryErrorResetBoundary,
211 * useSuspenseQueries,
212 * } from '@tanstack/preact-query'
213 * import type { ComponentChildren } from 'preact'
214 *
215 * function Posts({ ids }: { ids: Array<number> }) {
216 * // Every result is guaranteed to be defined — no per-query `isPending` check needed.
217 * const postQueries = useSuspenseQueries({
218 * queries: ids.map((id) => ({
219 * queryKey: ['post', id],
220 * queryFn: () => fetchPost(id),
221 * })),
222 * })
223 *
224 * return (
225 * <ul>
226 * {postQueries.map((query) => (
227 * <li key={query.data.id}>{query.data.title}</li>
228 * ))}
229 * </ul>
230 * )
231 * }
232 *
233 * function App() {
234 * return (
235 * <QueryErrorResetBoundary>
236 * {({ reset }) => (
237 * <ErrorBoundary
238 * onReset={reset}
239 * fallbackRender={({ resetErrorBoundary }) => (
240 * <div>
241 * There was an error!
242 * <button onClick={() => resetErrorBoundary()}>Try again</button>
243 * </div>
244 * )}
245 * >
246 * <Suspense fallback={<h1>Loading posts...</h1>}>
247 * <Posts ids={[1, 2, 3]} />
248 * </Suspense>
249 * </ErrorBoundary>
250 * )}
251 * </QueryErrorResetBoundary>
252 * )
253 * }
254 *
255 * function ErrorBoundary({
256 * children,
257 * onReset,
258 * fallbackRender,
259 * }: {
260 * children: ComponentChildren
261 * onReset: () => void
262 * fallbackRender: (props: {
263 * error: Error
264 * resetErrorBoundary: () => void
265 * }) => ComponentChildren
266 * }) {
267 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
268 *
269 * if (error) return fallbackRender({ error, resetErrorBoundary })
270 *
271 * return children
272 * }
273 * ```
274 *
275 * @example
276 * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so
277 * they fetch in parallel rather than suspending one after another:
278 * ```tsx
279 * import { Suspense } from 'preact/compat'
280 * import { useErrorBoundary } from 'preact/hooks'
281 * import {
282 * QueryErrorResetBoundary,
283 * useSuspenseQueries,
284 * } from '@tanstack/preact-query'
285 * import type { ComponentChildren } from 'preact'
286 *
287 * function Dashboard() {
288 * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({
289 * queries: [
290 * { queryKey: ['users'], queryFn: fetchUsers },
291 * { queryKey: ['teams'], queryFn: fetchTeams },
292 * { queryKey: ['projects'], queryFn: fetchProjects },
293 * ],
294 * })
295 *
296 * return (
297 * <div>
298 * <UserList users={usersQuery.data} />
299 * <TeamList teams={teamsQuery.data} />
300 * <ProjectList projects={projectsQuery.data} />
301 * </div>
302 * )
303 * }
304 *
305 * function App() {
306 * return (
307 * <QueryErrorResetBoundary>
308 * {({ reset }) => (
309 * <ErrorBoundary
310 * onReset={reset}
311 * fallbackRender={({ resetErrorBoundary }) => (
312 * <div>
313 * There was an error!
314 * <button onClick={() => resetErrorBoundary()}>Try again</button>
315 * </div>
316 * )}
317 * >
318 * <Suspense fallback={<h1>Loading dashboard...</h1>}>
319 * <Dashboard />
320 * </Suspense>
321 * </ErrorBoundary>
322 * )}
323 * </QueryErrorResetBoundary>
324 * )
325 * }
326 *
327 * function ErrorBoundary({
328 * children,
329 * onReset,
330 * fallbackRender,
331 * }: {
332 * children: ComponentChildren
333 * onReset: () => void
334 * fallbackRender: (props: {
335 * error: Error
336 * resetErrorBoundary: () => void
337 * }) => ComponentChildren
338 * }) {
339 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
340 *
341 * if (error) return fallbackRender({ error, resetErrorBoundary })
342 *
343 * return children
344 * }
345 * ```
346 *
347 * @example
348 * `combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes,
349 * not on every individual query update. This overload is the only one that accepts `combine`:
350 * ```tsx
351 * import { Suspense } from 'preact/compat'
352 * import { useErrorBoundary } from 'preact/hooks'
353 * import {
354 * QueryErrorResetBoundary,
355 * useSuspenseQueries,
356 * } from '@tanstack/preact-query'
357 * import type { ComponentChildren } from 'preact'
358 *
359 * function Refresh() {
360 * const anyFetching = useSuspenseQueries({
361 * queries: [
362 * { queryKey: ['users'], queryFn: fetchUsers },
363 * { queryKey: ['teams'], queryFn: fetchTeams },
364 * ],
365 * combine: (results) => results.some((result) => result.isFetching),
366 * })
367 *
368 * return anyFetching ? <span>Refreshing…</span> : null
369 * }
370 *
371 * function App() {
372 * return (
373 * <QueryErrorResetBoundary>
374 * {({ reset }) => (
375 * <ErrorBoundary
376 * onReset={reset}
377 * fallbackRender={({ resetErrorBoundary }) => (
378 * <div>
379 * There was an error!
380 * <button onClick={() => resetErrorBoundary()}>Try again</button>
381 * </div>
382 * )}
383 * >
384 * <Suspense fallback={<h1>Loading dashboard...</h1>}>
385 * <Refresh />
386 * </Suspense>
387 * </ErrorBoundary>
388 * )}
389 * </QueryErrorResetBoundary>
390 * )
391 * }
392 *
393 * function ErrorBoundary({
394 * children,
395 * onReset,
396 * fallbackRender,
397 * }: {
398 * children: ComponentChildren
399 * onReset: () => void
400 * fallbackRender: (props: {
401 * error: Error
402 * resetErrorBoundary: () => void
403 * }) => ComponentChildren
404 * }) {
405 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
406 *
407 * if (error) return fallbackRender({ error, resetErrorBoundary })
408 *
409 * return children
410 * }
411 * ```
412 */
413export function useSuspenseQueries<
414 T extends Array<any>,
415 TCombinedResult = SuspenseQueriesResults<T>,
416>(
417 options: {
418 /**
419 * An array with query option objects identical to `useSuspenseQuery`.
420 */
421 queries:
422 | readonly [...SuspenseQueriesOptions<T>]
423 | readonly [...{ [K in keyof T]: GetUseSuspenseQueryOptions<T[K]> }]
424 /**
425 * Use this to combine the results of the queries into a single value. The result will be structurally
426 * shared to be as referentially stable as possible.
427 */
428 combine?: (result: SuspenseQueriesResults<T>) => TCombinedResult
429 },
430 queryClient?: QueryClient,
431): TCombinedResult
432
433/**
434 * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed`
435 * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`.
436 *
437 * @param options - The `queries` array to run in Suspense, and an optional `combine` function.
438 * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
439 * will be used.
440 * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be
441 * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived
442 * flags set accordingly).
443 *
444 * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone
445 * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid
446 * this, make sure to set a high enough `staleTime`. Cancellation does not work.
447 *
448 * @example
449 * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
450 * required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
451 * Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
452 * ```tsx
453 * import { Suspense } from 'preact/compat'
454 * import { useErrorBoundary } from 'preact/hooks'
455 * import {
456 * QueryErrorResetBoundary,
457 * useSuspenseQueries,
458 * } from '@tanstack/preact-query'
459 * import type { ComponentChildren } from 'preact'
460 *
461 * function Posts({ ids }: { ids: Array<number> }) {
462 * // Every result is guaranteed to be defined — no per-query `isPending` check needed.
463 * const postQueries = useSuspenseQueries({
464 * queries: ids.map((id) => ({
465 * queryKey: ['post', id],
466 * queryFn: () => fetchPost(id),
467 * })),
468 * })
469 *
470 * return (
471 * <ul>
472 * {postQueries.map((query) => (
473 * <li key={query.data.id}>{query.data.title}</li>
474 * ))}
475 * </ul>
476 * )
477 * }
478 *
479 * function App() {
480 * return (
481 * <QueryErrorResetBoundary>
482 * {({ reset }) => (
483 * <ErrorBoundary
484 * onReset={reset}
485 * fallbackRender={({ resetErrorBoundary }) => (
486 * <div>
487 * There was an error!
488 * <button onClick={() => resetErrorBoundary()}>Try again</button>
489 * </div>
490 * )}
491 * >
492 * <Suspense fallback={<h1>Loading posts...</h1>}>
493 * <Posts ids={[1, 2, 3]} />
494 * </Suspense>
495 * </ErrorBoundary>
496 * )}
497 * </QueryErrorResetBoundary>
498 * )
499 * }
500 *
501 * function ErrorBoundary({
502 * children,
503 * onReset,
504 * fallbackRender,
505 * }: {
506 * children: ComponentChildren
507 * onReset: () => void
508 * fallbackRender: (props: {
509 * error: Error
510 * resetErrorBoundary: () => void
511 * }) => ComponentChildren
512 * }) {
513 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
514 *
515 * if (error) return fallbackRender({ error, resetErrorBoundary })
516 *
517 * return children
518 * }
519 * ```
520 *
521 * @example
522 * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so
523 * they fetch in parallel rather than suspending one after another:
524 * ```tsx
525 * import { Suspense } from 'preact/compat'
526 * import { useErrorBoundary } from 'preact/hooks'
527 * import {
528 * QueryErrorResetBoundary,
529 * useSuspenseQueries,
530 * } from '@tanstack/preact-query'
531 * import type { ComponentChildren } from 'preact'
532 *
533 * function Dashboard() {
534 * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({
535 * queries: [
536 * { queryKey: ['users'], queryFn: fetchUsers },
537 * { queryKey: ['teams'], queryFn: fetchTeams },
538 * { queryKey: ['projects'], queryFn: fetchProjects },
539 * ],
540 * })
541 *
542 * return (
543 * <div>
544 * <UserList users={usersQuery.data} />
545 * <TeamList teams={teamsQuery.data} />
546 * <ProjectList projects={projectsQuery.data} />
547 * </div>
548 * )
549 * }
550 *
551 * function App() {
552 * return (
553 * <QueryErrorResetBoundary>
554 * {({ reset }) => (
555 * <ErrorBoundary
556 * onReset={reset}
557 * fallbackRender={({ resetErrorBoundary }) => (
558 * <div>
559 * There was an error!
560 * <button onClick={() => resetErrorBoundary()}>Try again</button>
561 * </div>
562 * )}
563 * >
564 * <Suspense fallback={<h1>Loading dashboard...</h1>}>
565 * <Dashboard />
566 * </Suspense>
567 * </ErrorBoundary>
568 * )}
569 * </QueryErrorResetBoundary>
570 * )
571 * }
572 *
573 * function ErrorBoundary({
574 * children,
575 * onReset,
576 * fallbackRender,
577 * }: {
578 * children: ComponentChildren
579 * onReset: () => void
580 * fallbackRender: (props: {
581 * error: Error
582 * resetErrorBoundary: () => void
583 * }) => ComponentChildren
584 * }) {
585 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
586 *
587 * if (error) return fallbackRender({ error, resetErrorBoundary })
588 *
589 * return children
590 * }
591 * ```
592 */
593export function useSuspenseQueries<
594 T extends Array<any>,
595 TCombinedResult = SuspenseQueriesResults<T>,
596>(
597 options: {
598 /**
599 * An array with query option objects identical to `useSuspenseQuery`.
600 */
601 queries: readonly [...SuspenseQueriesOptions<T>]
602 /**
603 * Use this to combine the results of the queries into a single value. The result will be structurally
604 * shared to be as referentially stable as possible.
605 */
606 combine?: (result: SuspenseQueriesResults<T>) => TCombinedResult
607 },
608 queryClient?: QueryClient,
609): TCombinedResult
610
611export function useSuspenseQueries(options: any, queryClient?: QueryClient) {
612 return useQueries(
613 {
614 ...options,
615 queries: options.queries.map((query: any) => {
616 if (process.env.NODE_ENV !== 'production') {
617 if (query.queryFn === skipToken) {
618 console.error('skipToken is not allowed for useSuspenseQueries')
619 }
620 }
621
622 return {
623 ...query,
624 suspense: true,
625 throwOnError: defaultThrowOnError,
626 enabled: true,
627 placeholderData: undefined,
628 }
629 }),
630 },
631 queryClient,
632 )
633}