@@ -9,7 +9,7 @@ import Lobby from './Lobby/Lobby';
99import Game from './Game/Game' ;
1010
1111import { enterRoomByInvitationCode , selectUser , setUserId } from '../redux/slices/userSlice' ;
12- import { selectInvitationCode } from '@/redux/slices/roomSlice' ;
12+ import { selectInvitationCode , setInvitationCode } from '@/redux/slices/roomSlice' ;
1313
1414import db from '../../firebase/firebase.config' ;
1515import { LOCAL_STORAGE_ID , LOCAL_STORAGE_INVITATION_CODE } from '@/constants/localStorage' ;
@@ -35,26 +35,44 @@ export default function Home() {
3535 const fetchGameFromFirebase = async ( invitationCode : InvitationCode ) => {
3636 const gameRef = ref ( db , 'games/' + invitationCode ) ;
3737 const snapshot = await get ( gameRef ) ;
38+ return snapshot . exists ( ) ;
39+ } ;
3840
41+ const fetchRoomFromFirebase = async ( invitationCode : InvitationCode ) => {
42+ const roomRef = ref ( db , 'rooms/' + invitationCode ) ;
43+ const snapshot = await get ( roomRef ) ;
3944 return snapshot . exists ( ) ;
4045 } ;
4146
42- const handleGameData = ( exists : boolean , storagedId : UserId , storagedInvitationCode : InvitationCode ) => {
43- if ( exists ) {
44- dispatch ( setUserId ( storagedId ) ) ;
47+ const handleStateRestoration = (
48+ gameExists : boolean ,
49+ roomExists : boolean ,
50+ storagedId : UserId ,
51+ storagedInvitationCode : InvitationCode ,
52+ ) => {
53+ dispatch ( setUserId ( storagedId ) ) ;
54+ if ( gameExists ) {
55+ // 게임 진행 중 상태 복원
4556 dispatch ( enterRoomByInvitationCode ( storagedInvitationCode ) ) ;
57+ dispatch ( setInvitationCode ( null ) ) ; // 게임 상태에서는 room 코드를 null로 설정
58+ } else if ( roomExists ) {
59+ // 로비 상태 복원
60+ dispatch ( setInvitationCode ( storagedInvitationCode ) ) ;
4661 } else {
62+ // 유효하지 않은 상태 (게임도 방도 없음)
4763 localStorage . removeItem ( LOCAL_STORAGE_ID ) ;
4864 localStorage . removeItem ( LOCAL_STORAGE_INVITATION_CODE ) ;
65+ dispatch ( setUserId ( null ) ) ; // 유저 상태도 초기화
4966 }
5067 } ;
5168
5269 const fetchData = async ( ) => {
5370 const { storagedId, storagedInvitationCode } = getLocalStorageData ( ) ;
5471
5572 if ( storagedId && storagedInvitationCode ) {
56- const exists = await fetchGameFromFirebase ( storagedInvitationCode ) ;
57- handleGameData ( exists , storagedId , storagedInvitationCode ) ;
73+ const gameExists = await fetchGameFromFirebase ( storagedInvitationCode ) ;
74+ const roomExists = await fetchRoomFromFirebase ( storagedInvitationCode ) ;
75+ handleStateRestoration ( gameExists , roomExists , storagedId , storagedInvitationCode ) ;
5876 }
5977 } ;
6078
0 commit comments