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

index.tsx

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