import React, { ReactElement } from 'react';
import { FallbackComponent } from './Fallback';
import { logger } from '@cdm-logger/client';
import { useDispatch } from 'react-redux';

type IErrorBoundryState = { hasError: boolean; error: Error | null };
type IErrorBoundryProps = {
    children: ReactElement;
};

export class ErrorBoundary extends React.Component<IErrorBoundryProps, IErrorBoundryState> {
    constructor(props: IErrorBoundryProps) {
        super(props);
        this.state = { hasError: false, error: null };
    }

    static getDerivedStateFromError(error: Error) {
        return { hasError: true, error };
    }

    componentDidCatch(error: Error) {
        logger.debug(error);
    }

    render() {
        if (this.state.hasError) {
            return <FallbackComponent error={this.state.error as Error} />;
        }
        return this.props.children;
    }
}
