import React, { PropsWithChildren, ReactNode } from "react";

export interface ErrorBoundaryState {
  hasError: boolean;
}
export interface ErrorBoundaryProps {
  errorFallback: ReactNode;
}

export class ErrorBoundary extends React.Component<
  PropsWithChildren<ErrorBoundaryProps>,
  ErrorBoundaryState
> {
  constructor(props: any) {
    super(props);
    this.state = {
      hasError: false
    };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    // tslint:disable
    console.error("loading error:   ", error, errorInfo);
    // tslint:enable
    this.setState({
      hasError: true
    });
  }

  render() {
    const { errorFallback = null, children } = this.props;
    const { hasError } = this.state;
    return hasError ? errorFallback : children;
  }
}
