adds proper flow annotation and an option to specify a fallback component

This commit is contained in:
Sebastian Sdorra
2019-03-14 10:08:34 +01:00
parent df480b3a49
commit d2c99b9b8b

View File

@@ -1,26 +1,48 @@
// @flow // @flow
import React from "react"; import * as React from "react";
import ErrorNotification from "./ErrorNotification"; import ErrorNotification from "./ErrorNotification";
class ErrorBoundary extends React.Component { type Props = {
constructor(props) { fallback?: React.ComponentType<any>,
children: React.Node
};
type ErrorInfo = {
componentStack: string
};
type State = {
error?: Error,
errorInfo?: ErrorInfo
};
class ErrorBoundary extends React.Component<Props,State> {
constructor(props: Props) {
super(props); super(props);
this.state = { error: null, errorInfo: null }; this.state = {};
} }
componentDidCatch(error, errorInfo) { componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// Catch errors in any components below and re-render with error message // Catch errors in any components below and re-render with error message
this.setState({ this.setState({
error: error, error,
errorInfo: errorInfo errorInfo
}); });
} }
renderError = () => {
let FallbackComponent = this.props.fallback;
if (!FallbackComponent) {
FallbackComponent = ErrorNotification;
}
return <FallbackComponent {...this.state} />;
};
render() { render() {
if (this.state.errorInfo) { const { error } = this.state;
return ( if (error) {
<ErrorNotification error={this.state.error} /> return this.renderError();
);
} }
return this.props.children; return this.props.children;
} }