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

query-boundary.tsx

93 lines2.6 KB

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