import React from 'react'
import PropTypes from 'prop-types'
import {noop} from 'common-fe/utils'

class ErrorBoundary extends React.Component {
    state = {isError: false}

    componentDidCatch(error, info) {
        this.setState({isError: true}, () => {
            this.props.onError(error, info)
        })
    }

    render() {
        const {errorUI: ErrorComponent, children} = this.props

        return this.state.isError ? <ErrorComponent /> : children
    }
}

ErrorBoundary.propTypes = {
    errorUI: PropTypes.func.isRequired,
    children: PropTypes.node,
    onError: PropTypes.func,
}

ErrorBoundary.defaultProps = {
    onError: noop,
}

export default ErrorBoundary
