Last active
October 30, 2020 20:44
-
-
Save abinavseelan/e278d9c5f39064a21bf9b3174f40d8a5 to your computer and use it in GitHub Desktop.
ErrorBoundary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
class ErrorBoundary extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
error: null, | |
errorInfo: null, | |
}; | |
} | |
static getDerivedStateFromError() { | |
return { error: true }; | |
} | |
componentDidCatch(error, info) { | |
this.setState({ | |
error, | |
errorInfo: info | |
}); | |
} | |
render() { | |
const { error, errorInfo } = this.state; | |
const { children } = this.props; | |
if (error) { | |
return ( | |
<React.Fragment> | |
<h1>Something went wrong!</h1> | |
{ | |
__DEV__ | |
? ( | |
// show more details only when in development | |
<details> | |
<pre>{error && error.toString()}</pre> | |
<br /> | |
<pre>{errorInfo && errorInfo.componentStack}</pre> | |
</details> | |
) | |
: ( | |
null | |
) | |
} | |
</React.Fragment> | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment