import { Component } from 'react';
import type { ReactElement } from 'react';

interface ErrorBoundaryProps {
    children: ReactElement;
    onError: (error: Error, extra: { extra: any }) => void;
}

interface ErrorBoundaryState {
    hasError: boolean;
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
    static getDerivedStateFromError(): ErrorBoundaryState {
        return { hasError: true };
    }

    constructor(props: ErrorBoundaryProps) {
        super(props);
        this.state = { hasError: false };
    }

    componentDidCatch(error: Error, extra: any) {
        const { onError } = this.props;
        onError(error, { extra });
    }

    render() {
        const { children } = this.props;
        const { hasError } = this.state;
        if (hasError) {
            return null;
        }
        return children;
    }
}

export default ErrorBoundary;
