NextJs - 브라우저 뒤로가기 이벤트

Hunter Joe·2025년 1월 14일
0

기술 스택

Next.js 15.1.x (app router)
shadcn/ui

브라우저 뒤로가기 이벤트

브라우저에서 뒤로가기 이벤트를 클릭하면 작성한 게시글이 어떠한 경고도 없이 사라지는 것을 방지하기 위해서 구현해봄

바로 코드로 들어가보겠음

export default function WritePage() {
  const [showModal, setShowModal] = useState<boolean>(false)
  
    const onClickContinue = () => {
    if (showModal) {
      deleteImage(imageUrl); // continue 버튼을 누르면 올라가 있는 이미지 삭제
      setShowModal(false);
      window.history.back();
    }
  };

  useEffect(() => {
    window.history.pushState(null, '', window.location.href);

    const handlePopState = () => {
      console.log('popstate triggered'); // test console
      setShowModal(true);
    };

    window.addEventListener('popstate', handlePopState);
	
    // clean up fn
    return () => {
      window.removeEventListener('popstate', handlePopState);
    };
  }, []);
  
  return(
  // ...code 
  {/* Escape Modal */}
    {showModal && <EscapeModal showModal={showModal} onContinue={onClickContinue} />}
  )
}

주의 할 점

개발 환경에서는 "confirm"버튼을 누른 뒤에 한번 더 모달이 뜨는 에러가 발생함

npm run build 후에 테스트 해보면 정상적으로 모달이 한번만 뜨게 된다.
(아직 이유는 정확히 모르겠음)

아마도 strict모드 때문에 pushState가 두번 일어나서 이러한 상황이 일어난 것은 아닐까 조심스럽게 유추하곤 있다.

참고자료

profile
Async FE 취업 준비중.. Await .. (취업완료 대기중) ..

0개의 댓글

관련 채용 정보