Created
April 13, 2023 09:27
-
-
Save carlosazaustre/455d0b0406a78180c0304913e6374474 to your computer and use it in GitHub Desktop.
ErrorBoundary Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Suspense, lazy } from "react"; | |
import { ErrorBoundary, ErrorMessage } from "./Counter"; | |
import "./App.css"; | |
const Counter = lazy(() => import("./Counter")); | |
function App() { | |
return ( | |
<div className="App"> | |
<Suspense fallback={<p>Loading...</p>}> | |
<ErrorBoundary fallback={<ErrorMessage />}> | |
<Counter /> | |
</ErrorBoundary> | |
</Suspense> | |
</div> | |
); | |
} | |
export default App; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect, Component } from "react"; | |
export class ErrorBoundary extends Component { | |
state = { hasError: false }; | |
static getDerivedStateFromError(error) { | |
return { hasError: true }; | |
} | |
componentDidCatch(error, info) { | |
console.error(error, info.componentStack); | |
} | |
render() { | |
if (this.state.hasError) { | |
return this.props.fallback; | |
} | |
return this.props.children; | |
} | |
} | |
export function ErrorMessage() { | |
return <p style={{ border: "1px solid red" }}>Something went wrong</p>; | |
} | |
export default function Counter() { | |
const [count, setCount] = useState(0); | |
useEffect(() => { | |
if (count === 3) { | |
throw new Error("Counter reached 3"); | |
} | |
}, [count]); | |
return ( | |
<div> | |
<p>Count: {count}</p> | |
<button onClick={() => setCount(count + 1)}>Increment</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment