Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useSuspenseQueries.ts

629 lines21.7 KB

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