import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

export const useStateLocation = <StateType>(route: string = '/') => {
  const navigate = useNavigate();
  const { state } = useLocation();
  const stateLocation = state as StateType;

  useEffect(() => {
    if (!stateLocation) {
      navigate(route, { replace: true });
    }
  }, [stateLocation, navigate]);

  return stateLocation;
};

export default useStateLocation;
