Open History to see the last commit
1import {
2 ErrorBoundary,
3 Match,
4 Suspense,
5 Switch,
6 children,
7 untrack,
8} from 'solid-js'
9import type { UseQueryResult } from '@tanstack/solid-query'
10import type { JSX } from 'solid-js'
11β
12export interface QueryBoundaryProps<T = unknown> {
13 query: UseQueryResult<T, Error>
14β
15 /** Triggered when the data is initially loading. */
16 loadingFallback?: JSX.Element
17β
18 /** Triggered when fetching is complete, but the returned data was falsey. */
19 notFoundFallback?: JSX.Element
20β
21 /** Triggered when the query results in an error. */
22 errorFallback?: (err: Error, retry: () => void) => JSX.Element
23β
24 /** Triggered when fetching is complete, and the returned data is not falsey. */
25 children: (data: Exclude<T, null | false | undefined>) => JSX.Element
26}
27β
28/**
29 * Convenience wrapper that handles suspense and errors for queries. Makes the
30 * results of query.data available to children (as a render prop) in a type-safe
31 * way.
32 */
33export function QueryBoundary<T>(props: QueryBoundaryProps<T>) {
34 const retry = async (reset: () => void) => {
35 await untrack(() => props.query).refetch()
36 reset()
37 }
38β
39 return (
40 <Suspense fallback={props.loadingFallback}>
41 <ErrorBoundary
42 fallback={(err: Error, reset) =>
43 props.errorFallback ? (
44 props.errorFallback(err, () => retry(reset))
45 ) : (
46 <div>
47 <div class="error">{err.message}</div>
48 <button onClick={() => retry(reset)}>retry</button>
49 </div>
50 )
51 }
52 >
53 <Switch>
54 {/* <Match when={props.query.isError}>
55 {props.errorFallback ? (
56 props.errorFallback
57 ) : (
58 <div>
59 <div class="error">{props.query.error?.message}</div>
60 <button
61 onClick={() => {
62 props.query.refetch();
63 }}
64 >
65 retry
66 </button>
67 </div>
68 )}
69 </Match> */}
70β
71 <Match when={!props.query.isFetching && !props.query.data}>
72 {props.notFoundFallback ? (
73 props.notFoundFallback
74 ) : (
75 <div>not found</div>
76 )}
77 </Match>
78β
79 <Match when={props.query.data}>
80 {props.children(
81 props.query.data as Exclude<T, null | false | undefined>,
82 )}
83 </Match>
84 </Switch>
85 </ErrorBoundary>
86 </Suspense>
87 )
88}