Skip to content

Instantly share code, notes, and snippets.

@LeeCheneler
Created October 19, 2019 21:41
Show Gist options
  • Select an option

  • Save LeeCheneler/170666fe66beaeb1be181f2eefe5bb33 to your computer and use it in GitHub Desktop.

Select an option

Save LeeCheneler/170666fe66beaeb1be181f2eefe5bb33 to your computer and use it in GitHub Desktop.
react error boundary example
import React from "react";
export const DefaultErrorFallback = () => {
return <span>Oops! Failed to load...</span>;
};
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