TIL 108. 2024-06-04

이준구·2024년 6월 28일
0

TIL 순서

목록 보기
110/119
post-thumbnail

저번 글에 이어, 차선책으로 선택한 방법을 이야기할 예정이다.
만약, 이전 과정을 보지 못하신 분은 아래의 링크를 통해 보고 오시면, 더 이해하기 쉽습니당~

👇🏻👇🏻👇🏻
https://velog.io/@leejungoo1396/history-API


해결방법 순서 4)

  • history.pushState(null, "", "") 위치: Main, Room 두 페이지로 변경 및 추가
  • 방나가기 로직: 뒤로가기, 방나가기 버튼을 각각 다르게 처리

const Mainpage = () => {
  // Main history 추가
  useEffect(() => {
    history.pushState(null, "", "/main");
  }, []);
}

const JoinMafiaRoom = () => {
  //room history 추가
 useEffect(() => {  
      history.pushState(data, "", "");


   // popState Event
    const handlePopstate = (e: PopStateEvent) => {
      socket.emit("exitRoom", roomId, userId);
      setIsExit(true);
    };

    // 이벤트 리스너 등록
    window.addEventListener("popstate", handlePopstate);
    // 이벤트 리스너 제거
    return () => window.removeEventListener("popstate", handlePopstate);
  }, []);
  
}

  • 아래의 방 나가기 로직:
    • history 관리를 위해 기존 router.replace("main")에서 history.go(back)으로 변경
    • 뒤로가기 및 방나가기 버튼에 대한 로직을 별도로 처리

const Loading = () => {
  const router = useRouter();
  const { setIsExit } = useExitStore();

  useEffect(() => {
      //router.replace("main");
    
      //뒤로가기
      if (isBack) {
        const back = (history.length - 2) * -1;
        history.go(back);
      }
      // 방나가기
      const back = (history.length - 1) * -1;
      history.go(back);

    return () => {
      setIsExit(false);
    };
  }, []);

  return (
    <section className={`${S.loadingWrapper} ${designer.className}`}>
      <div>IceCraft</div>
      <div>Loading...</div>
      <div>메인페이지로 이동중 입니다.</div>
    </section>
  );
};

export default Loading;

  • 방 입장 시 history 목록 및 현재 내 위치
  • 뒤로 가기 시 history 목록 및 현재 내 위치

    • 1-1)
    • 1-2)

  • 방 나가기 클릭 시 history 목록 및 현재 내 위치

    • 2-1)
    • 2-2)

PopState 커스텀 훅으로 변경

import React, { useEffect, useState } from "react";

const usePopStateHandler = () => {
  const [isBack, setIsBack] = useState(false);

  useEffect(() => {
    //Room history 추가
    history.pushState(null, "", "");

    const handlePopstate = (e: PopStateEvent) => {
      setIsBack(true);
    };

    // 이벤트 리스너 등록
    window.addEventListener("popstate", handlePopstate);
    // 이벤트 리스너 제거
    return () => window.removeEventListener("popstate", handlePopstate);
  }, []);

  return isBack;
};

export default usePopStateHandler;



📚📚 참고 문서)

profile
개발 중~~~ 내 자신도 발전 중😂🤣

0개의 댓글

관련 채용 정보