Builds for
1 pipeline
failed
in
1 minute 19 seconds
RoomInfo 컴포넌트 추가
Showing
2 changed files
with
60 additions
and
0 deletions
web/src/components/room/RoomInfo.tsx
0 → 100644
1 | +import React, { useCallback, useContext, useEffect, useState } from 'react'; | ||
2 | +import { useLocation, useParams } from 'react-router'; | ||
3 | +import SocketContext from '../../contexts/SocketContext'; | ||
4 | +import { MessageType } from '../common/types'; | ||
5 | +import { RoomData, UpdateRoomUser } from './types'; | ||
6 | + | ||
7 | +interface RoomInfoLocation { | ||
8 | + state: { roomData: RoomData } | ||
9 | +} | ||
10 | + | ||
11 | +export const RoomInfo: React.FC = () => { | ||
12 | + const socket = useContext(SocketContext); | ||
13 | + const location: RoomInfoLocation = useLocation(); | ||
14 | + | ||
15 | + const [ roomData, setRoomData ] = useState<RoomData>({ | ||
16 | + // 기본값 | ||
17 | + uuid: '0', | ||
18 | + name: 'loading...', | ||
19 | + maxUsers: 9, | ||
20 | + users: [] | ||
21 | + }); | ||
22 | + | ||
23 | + const handleUpdateRoomUser = useCallback((data: UpdateRoomUser) => { | ||
24 | + if (data.state == 'added') { | ||
25 | + setRoomData({ | ||
26 | + ...roomData, | ||
27 | + users: [data.user, ...roomData.users] // TODO: immutable.js로 바꾸면 좋을 듯 | ||
28 | + }); | ||
29 | + } else if (data.state == 'removed') { | ||
30 | + const newUsers = roomData.users; | ||
31 | + const index = newUsers.indexOf(data.user); | ||
32 | + if (index < 0) { | ||
33 | + console.log('존재하지 않는 유저를 제거 시도'); | ||
34 | + } else { | ||
35 | + newUsers.splice(index, 1); | ||
36 | + } | ||
37 | + setRoomData({ | ||
38 | + ...roomData, | ||
39 | + users: newUsers | ||
40 | + }); | ||
41 | + } | ||
42 | + }, [roomData]); | ||
43 | + | ||
44 | + useEffect(() => { | ||
45 | + setRoomData(location.state.roomData); | ||
46 | + socket.on(MessageType.ROOM_USER_UPDATE, handleUpdateRoomUser); | ||
47 | + | ||
48 | + return () => { | ||
49 | + socket.off(MessageType.ROOM_USER_UPDATE, handleUpdateRoomUser); | ||
50 | + } | ||
51 | + }, []); | ||
52 | + | ||
53 | + return ( | ||
54 | + <div className='m-3 flex items-center place-content-between'> | ||
55 | + <div>{roomData.name}</div> | ||
56 | + <div>{roomData.users.length}/{roomData.maxUsers}</div> | ||
57 | + </div> | ||
58 | + ); | ||
59 | +} | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
... | @@ -7,6 +7,7 @@ import SocketContext from '../contexts/SocketContext'; | ... | @@ -7,6 +7,7 @@ import SocketContext from '../contexts/SocketContext'; |
7 | export const Room: React.FC = () => { | 7 | export const Room: React.FC = () => { |
8 | return ( | 8 | return ( |
9 | <Main> | 9 | <Main> |
10 | + <RoomInfo /> | ||
10 | </Main> | 11 | </Main> |
11 | ); | 12 | ); |
12 | } | 13 | } |
... | \ No newline at end of file | ... | \ No newline at end of file | ... | ... |
-
Please register or login to post a comment