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

import { To } from './types';

export const RedirectTarget = ({ to }: { to: To }) => {
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    if (location.pathname !== '/') {
      navigate(to + '?target=' + location.pathname, { replace: true });
    } else {
      navigate(to, { replace: true });
    }
  }, [navigate, to, location.pathname]);

  return null;
};
