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