Skip to content

Instantly share code, notes, and snippets.

@carlosazaustre
Created April 13, 2023 09:27
Show Gist options
  • Save carlosazaustre/455d0b0406a78180c0304913e6374474 to your computer and use it in GitHub Desktop.
Save carlosazaustre/455d0b0406a78180c0304913e6374474 to your computer and use it in GitHub Desktop.
ErrorBoundary Example
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;
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