setGameId
가 실행된 직후 router.push()
를 실행하면 gameId
가 아직 업데이트되지 않아 이전 값이 유지되는 문제가 발생.zustand
의 set
함수는 비동기적으로 상태를 업데이트하므로 setGameId(gameId)
가 실행된 직후 gameId
를 읽으면 변경이 반영되지 않을 수 있음.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) 형태로 호출하면 상태가 업데이트된 후 콜백이 실행됨.
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(...)가 실행됨.