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

query-boundary.tsx

95 lines2.6 KB

1/* eslint-disable @typescript-eslint/no-non-null-assertion */
2​
3import type { CreateQueryResult } from '@tanstack/solid-query'
4import type { JSX } from 'solid-js'
5import { ErrorBoundary, Match, Suspense, Switch, children } from 'solid-js'
6​
7export interface QueryBoundaryProps<T = unknown> {
8 query: CreateQueryResult<T, Error>
9​
10 /**
11 * Triggered when the data is initially loading.
12 */
13 loadingFallback?: JSX.Element
14​
15 /**
16 * Triggered when fetching is complete, but the returned data was falsey.
17 */
18 notFoundFallback?: JSX.Element
19​
20 /**
21 * Triggered when the query results in an error.
22 */
23 errorFallback?: (err: Error, retry: () => void) => JSX.Element
24​
25 /**
26 * Triggered when fetching is complete, and the returned data is not falsey.
27 */
28 children: (data: Exclude<T, null | false | undefined>) => JSX.Element
30​
31/**
32 * Convenience wrapper that handles suspense and errors for queries. Makes the results of query.data available to
33 * children (as a render prop) in a type-safe way.
34 */
35export function QueryBoundary<T>(props: QueryBoundaryProps<T>) {
36 return (
37 <Suspense fallback={props.loadingFallback}>
38 <ErrorBoundary
39 fallback={(err: Error, reset) =>
40 props.errorFallback ? (
41 props.errorFallback(err, async () => {
42 await props.query.refetch()
43 reset()
44 })
45 ) : (
46 <div>
47 <div class="error">{err.message}</div>
48 <button
49 onClick={async () => {
50 await props.query.refetch()
51 reset()
52 }}
53 >
54 retry
55 </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 )