Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Error boundary in React JS not working

I have a component

import React, {Component} from 'react';

class Buggy extends Component {
    state = {greeting : 'Welcome'};

    componentDidMount() {
        throw new Error('An error has occured');
    }

    render() {
        return (
            <h2>{this.state.greeting}</h2>
        );
    }
}

export default Buggy;

And a typical ErrorBoundary class

import React, {Component} from 'react';

class ErrorBoundary extends Component {
    state = {error: null, errorInfo: null};

    componentDidCatch(error, errorInfo) {
        this.setState({
            error: error,
            errorInfo: errorInfo
        })
    }

    render() {
        if(this.state.errorInfo) {
            return (
                <div>
                    <h2>Oops! Something went wrong.</h2>
                </div>
            );
        }
        return this.props.children;
    }
}

export default ErrorBoundary;

In App.js

  <ErrorBoundary>
    <Buggy />
  </ErrorBoundary>
</Fragment>

Yet errors are not handled.

enter image description here

What am I doing wrong ?

like image 644
StrugglingCoder Avatar asked Mar 15 '26 02:03

StrugglingCoder


1 Answers

componentDidCatch() is used to log error information not to render fallback UI, use getDerivedStateFromError() for that purpose.

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

Error Boundaries

like image 64
Henok Tesfaye Avatar answered Mar 17 '26 15:03

Henok Tesfaye



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!