My React app is catching the error and correctly displaying my custom error message, but after a second it still displays the original error logging. So the fallback UI then get's replaced by the initial error screen.
Test component:
import React, { Component } from 'react';
export class Test extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<ErrorBoundary>
<Error></Error>
</ErrorBoundary>);
}
}
Error component:
import React, { Component } from 'react';
export class Error extends React.Component {
constructor(props) {
super(props);
}
render() {
return ({ test });
}
}
In the error component test is undefined, so that will throw a undefined error.
ErrorBoundary:
import React, { Component } from 'react';
export class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
console.log('initiated');
}
componentDidCatch(error, errorInfo) {
// Catch errors in any components below and re-render with error message
console.log('ERROR');
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}
render() {
console.log('STATE');
console.log(this.state.error);
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}
First this get's displayed:
Then after a second this get's displayed:
How can i solve this?
If a component crashes, ErrorBoundaries can prevent crashing everything and display a custom message in that component and keep other components alive (in tact), right?