import React, { type ComponentType, type PropsWithChildren } from 'react' import FallbackComponent, { type Props as FallbackComponentProps, } from './FallbackComponent' export type Props = PropsWithChildren<{ FallbackComponent: ComponentType onError?: (error: Error, stackTrace: string) => void }> type State = { error: Error | null } class ErrorBoundary extends React.Component { state: State = { error: null } static defaultProps: { FallbackComponent: ComponentType } = { FallbackComponent: FallbackComponent, } static getDerivedStateFromError(error: Error): State { return { error } } componentDidCatch(error: Error, info: { componentStack: string }) { if (typeof this.props.onError === 'function') { this.props.onError(error, info.componentStack) } } resetError: () => void = () => { this.setState({ error: null }) } render() { const { FallbackComponent } = this.props return this.state.error ? ( ) : ( this.props.children ) } } export default ErrorBoundary