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.

What am I doing wrong ?
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);
}
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