🛠️ 증상

🔍 원인

✅ 해결 방법

1. setGameId에 콜백 지원 기능 추가


import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface GameState {
  roomId: string | null;
  gameId: string | null;
  setRoomId: (roomId: string) => void;
  setGameId: (gameId: string, callback?: () => void) => void; // ✅ 콜백 추가
  clearRoomId: () => void;
  clearGameId: () => void;
}

const useGameStore = create<GameState>()(
  persist(
    (set) => ({
      roomId: null,
      gameId: null,
      setRoomId: (roomId: string) => set({ roomId }),

      // ✅ 상태 업데이트 후 콜백 실행 가능하도록 수정
      setGameId: (gameId: string, callback?: () => void) =>
        set((state) => {
          const newState = { ...state, gameId };
          callback?.(); // 상태 업데이트 후 콜백 실행
          return newState;
        }),

      clearRoomId: () => set({ roomId: null }),
      clearGameId: () => set({ gameId: null }),
    }),
    {
      name: 'game-storage',
    }
  )
);

export default useGameStore;

🔹 setGameId(gameId, callback) 형태로 호출하면 상태가 업데이트된 후 콜백이 실행됨.


2. 사용 (WebSocket 메시지에서 setGameId 호출 후 router.push 실행)


if (message.messageType === 'GAME_START') {
  console.log('🚀 게임이 시작되었습니다!');

  setGameId(message.payload.gameId, () => {
    console.log(`✅ gameId 설정 완료: ${message.payload.gameId}`);
    router.push(`/game/${message.payload.gameId}/1`);
  });
}

🔹 setGameId가 gameId 상태를 업데이트한 후에 router.push(...)가 실행됨.