Created
October 19, 2019 21:41
-
-
Save LeeCheneler/170666fe66beaeb1be181f2eefe5bb33 to your computer and use it in GitHub Desktop.
react error boundary example
This file contains hidden or 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
| import React from "react"; | |
| export const DefaultErrorFallback = () => { | |
| return <span>Oops! Failed to load...</span>; | |
| }; |
This file contains hidden or 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
| import React from "react"; | |
| import { DefaultErrorFallback } from "./default-error-fallback"; | |
| export interface ErrorBoundaryFallbackProps { | |
| error: Error; | |
| } | |
| export interface ErrorBoundaryProps { | |
| children: React.ReactNode; | |
| fallback: React.FunctionComponent<ErrorBoundaryFallbackProps>; | |
| } | |
| export interface ErrorBoundaryState { | |
| error: Error | null; | |
| } | |
| export class ErrorBoundary extends React.Component< | |
| ErrorBoundaryProps, | |
| ErrorBoundaryState | |
| > { | |
| static defaultProps = { | |
| fallback: DefaultErrorFallback, | |
| }; | |
| constructor(props: ErrorBoundaryProps) { | |
| super(props); | |
| this.state = { | |
| error: null, | |
| }; | |
| } | |
| static getDerivedStateFromError = (error: Error) => { | |
| return { error }; | |
| }; | |
| componentDidCatch = (error: Error, errorInfo: React.ErrorInfo) => { | |
| console.error(error, errorInfo); | |
| }; | |
| render = () => { | |
| const { error } = this.state; | |
| if (error === null) return this.props.children; | |
| return this.props.fallback({ | |
| error, | |
| }); | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment