I am trying to create an error boundary that will display a toast message, log the error to the console and reset the its children. Say I have this code:
<ErrorBoundary>
<ComponentThrowingAnError prop1="1" />
</ErrorBoundary>
So when ComponentThrowingAnError
throws an error I'd like ErrorBoundary
to catch it, log it and show a toast message and then reset / re-render <ComponentThrowingAnError />
with prop1="1"
. What I mean with reset / re-render is that if my ErrorBoundary is just implemented like this:
class ErrorBoundary extends React.Component {
componentDidCatch(error: Error) {
console.error(error);
message.error("An error occured. Please check the console.");
}
render() {
return this.props.children;
}
}
its children will still be broken, so the error gets re-thrown until the entire application breaks. Instead, I'd like to have the error boundary discard its children and re-render them, so that they get resetted to <ComponentThrowingAnError prop1="1" />
.
Is that possible or is there another way to achieve
Oh I forgot, of course, when the error gets thrown because the props cause them, that will still be an issue of course, but I don't want to account for that here. I want to catch errors occurring from inside the children.
Yeah, you could do something like:
class ErrorBoundary extends React.Component {
state = { errorCount: 0 }
componentDidCatch() {
this.setState((state) => ({ errorCount: state.errorCount + 1 }))
}
render() {
return (
<React.Fragment key={this.state.errorCount}>
{this.props.children}
</React.Fragment>
)
}
}
Changing "key" allow you to re-mount the component. You will still see the development error overlay in development mode, just press "ESC" when that happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With