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

index.jsx

94 lines2.5 KB

1import React, { lazy } from "react";
2import ReactDOM from "react-dom/client";
3import {
4 useQueryClient,
5 QueryClient,
6 QueryClientProvider,
7 QueryErrorResetBoundary,
8} from "@tanstack/react-query";
9import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
10import { ErrorBoundary } from "react-error-boundary";
11​
12import { fetchProjects } from "./queries";
13​
14import Button from "./components/Button";
15​
16const Projects = lazy(() => import("./components/Projects"));
17const Project = lazy(() => import("./components/Project"));
18​
19const queryClient = new QueryClient({
20 defaultOptions: {
21 queries: {
22 retry: 0,
23 suspense: true,
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(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 <React.Suspense fallback={<h1>Loading projects...</h1>}>
74 {showProjects ? (
75 activeProject ? (
76 <Project
77 activeProject={activeProject}
78 setActiveProject={setActiveProject}
79 />
80 ) : (
81 <Projects setActiveProject={setActiveProject} />
82 )
83 ) : null}
84 </React.Suspense>
85 </ErrorBoundary>
86 )}
87 </QueryErrorResetBoundary>
88 <ReactQueryDevtools initialIsOpen />
89 </>
90 );
92​
93const rootElement = document.getElementById("root");
94ReactDOM.createRoot(rootElement).render(<App />);