forked from btholt/complete-intro-to-react-v5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathErrorBoundary.js
More file actions
39 lines (35 loc) · 981 Bytes
/
ErrorBoundary.js
File metadata and controls
39 lines (35 loc) · 981 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// mostly code from reactjs.org/docs/error-boundaries.html
import React, { Component } from "react";
import { Link, Redirect } from "@reach/router";
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, redirect: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("ErrorBoundary caught an error", error, info);
}
componentDidUpdate() {
if (this.state.hasError) {
setTimeout(() => this.setState({ redirect: true }), 5000);
}
}
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;