RoomInfo.tsx 1.65 KB
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>
  );
}