RoomInfo.tsx
1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import React, { useCallback, useContext, useEffect, useState } from 'react';
import { useLocation, useParams } from 'react-router';
import SocketContext from '../../contexts/SocketContext';
import { MessageType } from '../common/types';
import { RoomData, UpdateRoomUser } from './types';
interface RoomInfoLocation {
state: { roomData: RoomData }
}
export const RoomInfo: React.FC = () => {
const socket = useContext(SocketContext);
const location: RoomInfoLocation = useLocation();
const [ roomData, setRoomData ] = useState<RoomData>({
// 기본값
uuid: '0',
name: 'loading...',
maxUsers: 9,
users: []
});
const handleUpdateRoomUser = useCallback((data: UpdateRoomUser) => {
if (data.state == 'added') {
setRoomData({
...roomData,
users: [data.user, ...roomData.users] // TODO: immutable.js로 바꾸면 좋을 듯
});
} else if (data.state == 'removed') {
const newUsers = roomData.users;
const index = newUsers.indexOf(data.user);
if (index < 0) {
console.log('존재하지 않는 유저를 제거 시도');
} else {
newUsers.splice(index, 1);
}
setRoomData({
...roomData,
users: newUsers
});
}
}, []);
useEffect(() => {
setRoomData(location.state.roomData);
socket.on(MessageType.ROOM_USER_UPDATE, handleUpdateRoomUser);
return () => {
socket.off(MessageType.ROOM_USER_UPDATE, handleUpdateRoomUser);
}
}, []);
return (
<div className='m-3 flex items-center place-content-between'>
<div>{roomData.name}</div>
<div>{roomData.users.length}/{roomData.maxUsers}</div>
</div>
);
}