Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React / Create an error boundary that resets its children

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

  • Catching and logging the error
  • And the resetting the children to their initial states / props?

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.

like image 785
Lukas Avatar asked Oct 16 '25 02:10

Lukas


1 Answers

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.

like image 190
Federkun Avatar answered Oct 18 '25 16:10

Federkun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!