I've got the following working JavaScript class.I'm hoping there is an ES6 way of doing it without having to use the constructor keyword and also minimize the use of this. I've tried statements like
state = {hasError: false}
and that works for just hasError, but can't figure out how to handle the function bind. I'm hoping not to have to do that like I don't have to use this to access state with the new syntax.
export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
this.updateHasErrorsToFalse = this.updateHasErrorsToFalse.bind(this);
}
updateHasErrorsToFalse() {
this.setState((prevState) => ({
hasError: false,
}));
}
//state = { hasError: false, error: null, };
static getDerivedStateFromError(error) {
return {
hasError: true,
error: error.message
};
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
console.log(error, errorInfo);
}
updateHasErrorsToFalse() {
this.setState((prevState) => ({
hasError: false,
}));
}
render() {
function addExtraProps(Component, extraProps) {
return <Component.type {...Component.props} {...extraProps} />;
}
if (this.state.hasError) {
return addExtraProps(this.props.fallback, {
error: this.state.error,
resetError: this.updateHasErrorsToFalse,
});
}
return this.props.children;
}
}
By doing the following, you bind this to function manually.
this.updateHasErrorsToFalse = this.updateHasErrorsToFalse.bind(this);
Instead of that, you can use the arrow function notation which has the lexical binding of this.
updateHasErrorsToFalse = () => {
this.setState((prevState) => ({
hasError: false,
}));
}
And you can remove constructor and have state instance as below.
Instead of
constructor(props) {
super(props);
this.state = { hasError: false };
this.updateHasErrorsToFalse = this.updateHasErrorsToFalse.bind(this);
}
Just keep following in the class level
state = { hasError: false };