Complete the code to create an error boundary component in Next.js.
import React from 'react'; function ErrorBoundary({ children }) { const [hasError, setHasError] = React.useState(false); React.useEffect(() => { const handleError = () => setHasError(true); window.addEventListener('error', handleError); return () => window.removeEventListener('error', [1]); }, []); if (hasError) { return <div>Something went wrong.</div>; } return children; }
The event listener must remove the exact same function it added. Here, handleError is the function to remove.
Complete the code to catch errors in a React component using Next.js error boundaries.
import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static [1](error) { return { hasError: true }; } render() { if (this.state.hasError) { return <h1>Oops! Something went wrong.</h1>; } return this.props.children; } }
getDerivedStateFromError is a static method used to update state when an error is caught in a React error boundary.
Fix the error in the Next.js error boundary component to properly log errors.
class ErrorBoundary extends React.Component { componentDidCatch(error, info) { console.log([1]); } render() { return this.props.children; } }
The componentDidCatch method receives two arguments: error and info. To log both, pass them as arguments to console.log.
Fill both blanks to create a functional error boundary using React hooks in Next.js.
import React from 'react'; function ErrorBoundary({ children }) { const [hasError, setHasError] = React.useState(false); React.useEffect(() => { const handleError = () => setHasError(true); window.addEventListener('error', [1]); return () => window.removeEventListener('error', [2]); }, []); if (hasError) { return <div>Oops! An error occurred.</div>; } return children; }
The same function handleError must be used for both adding and removing the event listener to properly manage the error event.
Fill all three blanks to create a dictionary comprehension that filters errors by severity in Next.js error logging.
const errorSummary = {
[1]: [2] for (const [key, value] of Object.entries(errors))
if (value.severity [3] 3)
};This code creates an object with keys and values from errors where the severity is 3 or higher.