import { Alert } from '@chakra-ui/react'
import React from 'react'

export class ErrorBoundary extends React.Component<
  React.PropsWithChildren,
  { hasError: boolean, error?: string }
> {
  state = { hasError: false, error: null }

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

  render() {
    if (this.state.hasError) {
      return (
        <Alert status="error" title="Ошибка">
          Что-то пошло не так<br />
          {this.state.error && <span>{this.state.error}</span>}
        </Alert>
      )
    }

    return this.props.children
  }
}
