Skip to content

Instantly share code, notes, and snippets.

@pkellner
Created January 30, 2022 14:59
Show Gist options
  • Save pkellner/c400d0b4d631b1709bed9422871b064b to your computer and use it in GitHub Desktop.
Save pkellner/c400d0b4d631b1709bed9422871b064b to your computer and use it in GitHub Desktop.
ErrorBoundary used in React 18 Pluralsight Course
// 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