Skip to content

Commit bffc7ce

Browse files
authored
Restore first version (#3205)
1 parent b0fc826 commit bffc7ce

File tree

1 file changed

+40
-13
lines changed

1 file changed

+40
-13
lines changed

ui/components/ErrorBoundary.tsx

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,64 @@
1-
import * as React from "react";
1+
import React, { useState, useEffect, FC } from "react";
2+
import { useLocation } from "react-router-dom";
23
import Page from "./Page";
34

4-
export default class ErrorBoundary extends React.Component<
5-
any,
6-
{ hasError: boolean; error: Error }
7-
> {
8-
constructor(props) {
5+
interface Props {
6+
hasError: boolean;
7+
error: Error | null;
8+
}
9+
10+
class ErrorBoundaryDetail extends React.Component<any, Props> {
11+
constructor(props: any) {
912
super(props);
1013
this.state = { hasError: false, error: null };
1114
}
1215

13-
static getDerivedStateFromError(error) {
14-
// Update state so the next render will show the fallback UI.
16+
static getDerivedStateFromError(error: Error) {
1517
return { hasError: true, error };
1618
}
1719

18-
componentDidCatch(error) {
19-
// You can also log the error to an error reporting service
20+
componentDidUpdate(prevProps: Props) {
21+
if (!this.props.hasError && prevProps.hasError) {
22+
this.setState({ hasError: false });
23+
}
24+
}
25+
26+
componentDidCatch(error: Error) {
2027
console.error(error);
28+
this.props.setHasError(true);
2129
}
2230

2331
render() {
2432
if (this.state.hasError) {
25-
// You can render any custom fallback UI
2633
return (
2734
<Page>
2835
<h3>Something went wrong.</h3>
29-
<pre>{this.state.error.message}</pre>
30-
<pre>{this.state.error.stack}</pre>
36+
<pre>{this.state.error?.message}</pre>
37+
<pre>{this.state.error?.stack}</pre>
3138
</Page>
3239
);
3340
}
3441

3542
return this.props.children;
3643
}
3744
}
45+
46+
/** Function component wrapper as we need useEffect to set the state back to false on location changing **/
47+
const ErrorBoundary: FC<{ children: React.ReactNode }> = ({ children }) => {
48+
const [hasError, setHasError] = useState<boolean>(false);
49+
const location = useLocation();
50+
51+
useEffect(() => {
52+
if (hasError) {
53+
setHasError(false);
54+
}
55+
}, [location.key]);
56+
57+
return (
58+
<ErrorBoundaryDetail hasError={hasError} setHasError={setHasError}>
59+
{children}
60+
</ErrorBoundaryDetail>
61+
);
62+
};
63+
64+
export default ErrorBoundary;

0 commit comments

Comments
 (0)