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

import './index.less';

const getKey = () => Math.random().toString(36).substr(2);

export function AppRedirect({ path, to }) {
  const history = useHistory();
  const location = useLocation();
  useEffect(() => {
    if (path === location.pathname) {
      if (typeof to !== 'string') {
        history.replace({ ...to, search: to.search ? `${to.search}&key=${getKey()}` : `?key=${getKey()}`, state: Object.assign({}, to.state, { isReplace: true }) });
      } else {
        history.push({ pathname: to, search: `?key${getKey()}`, state: { isReplace: true } });
      }
    }
  }, [path, location.pathname, to, history]);
  return null;
}

export default AppRedirect;
