Component Lifecycle componentDidCatch

This file can be called ErrorBoundary.js

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
import { Component } from "react";
import { Link } from "react-router-dom";

class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("ErrorBoundary caught an error", error, info);
}
render() {
if (this.state.hasError) {
return (
<h2>
There was an error with this listing. <Link to="/">Click here</Link>{" "}
to back to the home page or wait five seconds.
</h2>
);
}

return this.props.children;
}
}

export default ErrorBoundary;

Then wrap the child

1
2
3
4
5
6
7
8
9
10
11
12
13
// add import
import ErrorBoundary from "./ErrorBoundary";

// replace export
const DetailsWithRouter = withRouter(Details);

export default function DetailsErrorBoundary(props) {
return (
<ErrorBoundary>
<DetailsWithRouter {...props} />
</ErrorBoundary>
);
}