Listing 13-10: Using try/catch to catch errors in an ErrorBoundary
import {Component} from 'react';
import logger from './logger';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error,info){
try {
logger.push({ error, info });
} catch(error){
// handle the error here
}
}
render() {
if (this.state.hasError) {
return <h1>Oops! There's been an error.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.
