RoomBlock.tsx 1.72 KB
import React, { useCallback, useContext } from 'react';
import { useHistory } from 'react-router';
import SocketContext from '../../contexts/SocketContext';
import { MessageResponse, MessageType, RawMessage } from '../common/types';
import { RoomData } from '../room/types';
import { Room } from './types';

interface RoomBlockProps {
  room: Room
}

export const RoomBlock: React.FC<RoomBlockProps> = ({ room }) => {
  const history = useHistory();
  const socket = useContext(SocketContext);
  const joinRoom = useCallback(() => {
    if (room.currentUsers < room.maxUsers) {
      const rawMessage: RawMessage = {
        type: MessageType.ROOM_JOIN,
        message: { uuid: room.uuid }
      }
      socket.emit('msg', rawMessage, (response: MessageResponse<RoomData>) => {
        if (response.ok) {
          history.push({
            pathname: '/' + room.uuid,
            state: {roomData: response.result!}
          });
        } else {
          //TODO: 에러 MODAL을 어케띄우지? 하위컴포넌트에서 훅을 쓰면 어떻게 되는지 확인
        }
      })
    } else {
      //TODO: 자리 꽉찼다는 MODAL
    }
  }, []);

  return (
    <button className={`flex items-center place-content-between m-2 w-5/6 
                  ${room.currentUsers < room.maxUsers ?
                    'bg-white active:bg-green-100' :
                    'bg-gray-200 active:bg-gray-200'}
                  rounded shadow hover:shadow-md
                  outline-none focus:outline-none`}
            onClick={joinRoom}>
      <span className='mt-2 mb-2 ml-3 text-gray-600 text-lg'>{room.name}</span>
      <span className='mt-2 mb-2 mr-3 text-gray-500 text-right'>
        {room.currentUsers}/{room.maxUsers}
      </span>
    </button>
  );
}