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

index.tsx

98 lines2.6 KB

1import 'font-awesome/css/font-awesome.min.css'
2import React, { lazy } from 'react'
3import ReactDOM from 'react-dom/client'
4import {
5 QueryClient,
6 QueryClientProvider,
7 QueryErrorResetBoundary,
8 noop,
9 useQueryClient,
10} from '@tanstack/react-query'
11import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
12import { ErrorBoundary } from 'react-error-boundary'
13​
14import { fetchProjects } from './queries'
15​
16import Button from './components/Button'
17​
18const Projects = lazy(() => import('./components/Projects'))
19const Project = lazy(() => import('./components/Project'))
20​
21const queryClient = new QueryClient({
22 defaultOptions: {
23 queries: {
24 retry: 0,
25 },
26 },
27})
28​
29function App() {
30 return (
31 <QueryClientProvider client={queryClient}>
32 <Example />
33 </QueryClientProvider>
34 )
36​
37function Example() {
38 const queryClient = useQueryClient()
39 const [showProjects, setShowProjects] = React.useState(false)
40 const [activeProject, setActiveProject] = React.useState<string | null>(null)
41​
42 return (
43 <>
44 <Button
45 onClick={() => {
46 setShowProjects((old) => {
47 if (!old) {
48 queryClient
49 .query({
50 queryKey: ['projects'],
51 queryFn: fetchProjects,
52 })
53 .catch(noop)
54 }
55 return !old
56 })
57 }}
58 >
59 {showProjects ? 'Hide Projects' : 'Show Projects'}
60 </Button>
61​
62 <hr />
63​
64 <QueryErrorResetBoundary>
65 {({ reset }) => (
66 <ErrorBoundary
67 fallbackRender={({ error, resetErrorBoundary }) => (
68 <div>
69 There was an error!{' '}
70 <Button onClick={() => resetErrorBoundary()}>Try again</Button>
71 <pre style={{ whiteSpace: 'normal' }}>{error.message}</pre>
72 </div>
73 )}
74 onReset={reset}
75 >
76 {showProjects ? (
77 <React.Suspense fallback={<h1>Loading projects...</h1>}>
78 {activeProject ? (
79 <Project
80 activeProject={activeProject}
81 setActiveProject={setActiveProject}
82 />
83 ) : (
84 <Projects setActiveProject={setActiveProject} />
85 )}
86 </React.Suspense>
87 ) : null}
88 </ErrorBoundary>
89 )}
90 </QueryErrorResetBoundary>
91 <ReactQueryDevtools initialIsOpen />
92 </>
93 )
95​
96const rootElement = document.getElementById('root')
97if (!rootElement) throw new Error('Missing #root element')
98ReactDOM.createRoot(rootElement).render(<App />)