import { Component } from 'react';
import { useLocation } from 'react-router-dom';
import { useAuth } from '../../hooks';

class ErrorBoundary extends Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, info) {
  

    

    if (error.message === 'No connection established') {
      this.setState({
        ...this.state,
        hasError: true,
      });
    }
    // return { ...this.state, error, info };
    this.setState({
      ...this.state,
      error,
      info,
    });
  }

  componentDidUpdate(prevProps) {
    // Check if the route has changed
    if (this.props.location !== prevProps.location) {
      // Clear the error state
      this.setState({ hasError: false });
    }
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return this.props.fallback({
        error: this.state.error,
        info: this.state.info,
      });
    }

    return this.props.children;
  }
}

const ErrorBoundaryWithRouter = (props) => {
  const location = useLocation();

  return <ErrorBoundary {...props} location={location} />;
};

export default ErrorBoundaryWithRouter;
