Created
January 30, 2022 14:59
-
-
Save pkellner/c400d0b4d631b1709bed9422871b064b to your computer and use it in GitHub Desktop.
ErrorBoundary used in React 18 Pluralsight Course
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
// Author: Peter Kellner, https://peterkellner.net | |
import React from 'react'; | |
class ErrorBoundary extends React.Component { | |
state = { hasError: false }; | |
updateHasErrorsToFalse = () => { | |
this.setState(() => ({ | |
hasError: false, | |
})); | |
}; | |
static getDerivedStateFromError(error) { | |
// Update state so the next render will show the fallback UI. | |
return { hasError: true, error: error.message }; | |
} | |
componentDidCatch(error, errorInfo) { | |
// You can also log the error to an error reporting service | |
console.log(error, errorInfo); | |
} | |
render() { | |
if (this.state.hasError) { | |
function addExtraProps(Component, extraProps) { | |
return ( | |
<Component.type {...Component.props} {...extraProps} /> | |
); | |
} | |
return addExtraProps(this.props.fallback, { | |
error: this.state.error, | |
resetError: this.updateHasErrorsToFalse, | |
}); | |
} | |
return this.props.children; | |
} | |
} | |
export default ErrorBoundary; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment