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

query-boundary.tsx

72 lines1.9 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 { 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?: 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 <Switch>
39 <Match when={props.query.isError}>
40 {props.errorFallback ? (
41 props.errorFallback
42 ) : (
43 <div>
44 <div class="error">{props.query.error?.message}</div>
45 <button
46 onClick={() => {
47 props.query.refetch()
48 }}
49 >
50 retry
51 </button>
52 </div>
53 )}
54 </Match>
55​
56 <Match when={!props.query.isFetching && !props.query.data}>
57 {props.notFoundFallback ? (
58 props.notFoundFallback
59 ) : (
60 <div>not found</div>
61 )}
62 </Match>
63​
64 <Match when={props.query.data}>
65 {props.children(
66 props.query.data as Exclude<T, null | false | undefined>,
67 )}
68 </Match>
69 </Switch>
70 </Suspense>
71 )