Complete the code to define an error boundary component in React.
function ErrorBoundary({ children }) {
const [hasError, setHasError] = React.useState(false);
React.useEffect(() => {
window.addEventListener('error', () => setHasError(true));
}, []);
if ([1]) {
return <h1>Something went wrong.</h1>;
}
return children;
}The component uses the hasError state to check if an error occurred and conditionally render the fallback UI.
Complete the code to catch errors in a React component using an error boundary.
function BuggyComponent() {
throw new Error('Bug!');
}
function App() {
return (
<ErrorBoundary>
[1]
</ErrorBoundary>
);
}The BuggyComponent is wrapped inside the ErrorBoundary to catch its errors and prevent app crashes.
Fix the error in the error boundary component to properly catch errors using React hooks.
function ErrorBoundary({ children }) {
const [hasError, setHasError] = React.useState(false);
React.useEffect(() => {
try {
[1];
} catch {
setHasError(true);
}
}, []);
if (hasError) {
return <h1>Something went wrong.</h1>;
}
return children;
}Using window.addEventListener('error', ...) inside useEffect listens for errors and sets the error state.
Fill both blanks to create a React error boundary that resets error state on retry.
function ErrorBoundary({ children }) {
const [hasError, setHasError] = React.useState(false);
React.useEffect(() => {
const handleError = () => setHasError(true);
window.addEventListener('error', handleError);
return () => window.[1]('error', [2]);
}, []);
if (hasError) {
return <button onClick={() => setHasError(false)}>Try again</button>;
}
return children;
}We remove the error listener on cleanup using removeEventListener and the same handler handleError.
Fill all three blanks to create a Remix loader that handles errors gracefully with an error boundary.
import { json } from '@remix-run/node'; import { useLoaderData } from '@remix-run/react'; export async function loader() { try { const data = await fetch('/api/data').then(res => res.json()); return json(data); } catch (error) { throw new Response('Failed to load', { status: [1] }); } } export default function DataPage() { const data = useLoaderData(); return <div>[2]: [3]</div>; }
The loader throws a 500 status on error. The component displays the data with a label Error.
