generated from Exabyte-io/template-definitions
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
update: add error boundary to catch error and restore state
- Loading branch information
Showing
2 changed files
with
79 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import Button from "@mui/material/Button"; | ||
import React, { ReactNode } from "react"; | ||
|
||
interface ErrorBoundaryState { | ||
hasError: boolean; | ||
backup: ReactNode | null; | ||
} | ||
|
||
interface ErrorBoundaryProps { | ||
children: ReactNode; | ||
restore?: boolean; | ||
} | ||
|
||
class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> { | ||
constructor(props: ErrorBoundaryProps) { | ||
super(props); | ||
this.state = { | ||
hasError: false, | ||
backup: null, | ||
}; | ||
} | ||
|
||
componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void { | ||
console.error("Caught error:", error, errorInfo); | ||
|
||
// eslint-disable-next-line react/destructuring-assignment | ||
if (this.props.restore) { | ||
this.restore(); | ||
} | ||
} | ||
|
||
restore = (): void => { | ||
this.setState({ hasError: false }); | ||
}; | ||
|
||
render(): ReactNode { | ||
const { backup, hasError } = this.state; | ||
const { children, restore: restore1 } = this.props; | ||
if (hasError && !restore1) { | ||
return ( | ||
<div> | ||
<h1>Something went wrong.</h1> | ||
<button type="button" onClick={this.restore}> | ||
Try to restore | ||
</button> | ||
</div> | ||
); | ||
} | ||
|
||
if (backup === null) { | ||
this.setState({ backup: children }); | ||
} | ||
|
||
return children; | ||
} | ||
} | ||
|
||
export default ErrorBoundary; |