Objectives
Create a React app with:
BuggyCounter
component that throws an error if the counter exceeds 5.ErrorBoundary
to catch and handle the error.Starter Code:
// BuggyCounter.js
import React, { useState } from "react";
export function BuggyCounter({ count, setCount }: {
count: number;
setCount(count: number): void;
}) {
if (count > 5) {
throw new Error("Counter exceeded limit!");
}
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export function App() {
const [count, setCount] = useState(0);
return (
<BuggyCounter count={count} setCount={setCount} />
)
}
Remember that the structure of Error Boundary is as following:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state to show fallback UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log error details for debugging
console.error("Error caught by boundary:", error, errorInfo);
}
render() {
if (this.state.hasError) {
// Fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}