Typing an Error Boundary
https://frontendmasters.com/courses/intermediate-react-v2/typing-an-error-boundary/
Typing error boundary
// **** ErrorBoundary.tsx ****
import React, { Component, ErrorInfo } from "react";
import { Link, Redirect } from "@reach/router";
class ErrorBoundary extends Component {
// deletes the constructor...
//constructor(props) {
// super(props);
// this.state = { hasError: false, redirect: false };
// }
public state = {
redirect: "",
hasError: false
};
public static getDerivedStateFromError() {
return { hasError: true };
}
// set the types for error and info
public componentDidCatch(error: Error, info: ErrorInfo) {
console.error("ErrorBoundary caught an error", error, info);
}
public componentDidUpdate() {
if (this.state.hasError) {
setTimeout(() => this.setState({ redirect: true }), 5000);
}
}
public render() {
if (this.state.redirect) {
return <Redirect to="/" />;
}
if (this.state.hasError) {
return (
<h1>
There was an error with this listing. <Link to="/">Click here</Link>{" "}
to back to the home page or wait five seconds
</h1>
);
}
return this.props.children;
}
}
export default ErrorBoundary;