import { useLayoutEffect } from "react";
import { useHistory, useLocation } from "react-router-dom";

const useScrollY = () => {
  const location = useLocation();
  const history = useHistory();

  useLayoutEffect(() => {
    if (!location.state) {
      // if location state not exist, return
      return;
    }
    const { scrollY } = location.state as {
      scrollY?: number;
    };

    if (scrollY) {
      window.scrollTo({
        top: scrollY,
        left: 0,
        behavior: "smooth",
      });
      setTimeout(() => {
        history.replace("/");
      }, 100);
    }
  }, [history, location]);
};

export default useScrollY;
