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