I'm learning how to use componentDidCatch()
. It looks straight forward. It works, but to still show the complete error stack on view.
In separate files:
import React, { Component } from 'react' class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false } } componentDidCatch(error, info) { console.log("Catching an error") // this is never logged this.setState(state => ({...state, hasError: true })) } render() { if (this.state.hasError) { return <div>Sorry, an error occurred</div> } return this.props.children } } export default ErrorBoundary ... import React, { Component } from 'react' class Foo extends Component { render() { return this.props.a.b; // So this should cause the error } } export default Foo ... import React, { Component } from 'react' // Imported Foo and ErrorBoundary class Home extends Component { render() { return <ErrorBoundary><Foo /></ErrorBoundary> } } export default Home
On page refresh, I see Sorry, an error occurred
for, literally, a second then the full error stack displaying to the user. Is this an issue with Create React App? I'm using React 16.
With the new feature in React, developers can test the Error Boundaries by a toggle error button, added to the DevTools. When we click on the toggle error button on the component labeled 'Inner Component', Error boundary is triggered.
If you really need create-react-app , you might need to reinstall Node and reconfigure your dependencies to ensure you have a fresh start with Node, npm, npx, and the like.
Use componentDidCatch() to log error information. Error boundaries work like a JavaScript catch {} block, but for components. Only class components can be error boundaries. In practice, most of the time you'll want to declare an error boundary component once and use it throughout your application.
As per this issue on github,
On page refresh, I see Sorry, an error occurred for, literally, a second then the full error stack displaying to the user.
@DanAbramov has made it clear that
This is intentional. An unexpected error is still an error. (We don’t recommend using error boundaries for expected errors or control flow.)
Error boundaries are primarily useful for production, but in development we want to make errors as highly visible as possible.
Also The error visible is just an overlay and your ErrorBoundary
message gets hidden behind the Error overlay
To check if the Error is actually present, you can inspect element and delete the overlay from DOM, and you would be able to see the error message
Check this CodeSandbox:
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