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

interface CreateLocation {
  state: { username: string }
}

export const Create: React.FC = () => {
  const history = useHistory();
  const socket = useContext(SocketContext);
  const [ roomName, setRoomName ] = useState('');
  const location: CreateLocation = useLocation();

  const createRooms = useCallback(() => {
    const rawMessage: RawMessage = {
      type: MessageType.ROOM_LIST_CREATE,
      message: { name: roomName }
    }
    socket.emit('msg', rawMessage, (response: MessageResponse<RoomData>) => {
      if (response.ok) {
        history.push({
          pathname: '/' + response.result!.uuid,
          state: {
            username: location.state.username,
            roomData: response.result!
          }
        });
      } else {
        console.log('방 생성 오류');
      }
    });
  }, [roomName]);
  
  return (
    <div className="flex items-center">
      <input type="text"
                placeholder="Room name"
                className="h-8 px-3 py-1.5 bg-white
                    placeholder-gray-400 text-gray-700 text-sm
                    rounded shadow outline-none focus:outline-none"
                value={roomName}
                onChange={e => setRoomName(e.target.value)}
            />
      <button className="bg-green-500 active:bg-green-600
                            text-white uppercase text-xl
                            w-10 h-8 pb-0.5 ml-3 rounded shadow round
                            outline-none focus:outline-none hover:shadow-md
                            ease-linear transition-all duration-100"
                    type="button"
                    onClick={() => createRooms()}>+</button>
    </div>
  );
}