Word.tsx 1.33 KB
import React, { useCallback, useContext } from 'react';
import { IndexType } from 'typescript';
import SocketContext from '../../contexts/SocketContext';
import { MessageResponse, MessageType, RawMessage } from '../common/types';

interface WordProps {
  index: number;
  word: string;
  setWordChosen: (value: React.SetStateAction<string>) => void;
  setWords: (value: React.SetStateAction<string[]>) => void;
}

export const Word: React.FC<WordProps> = (props) => {
  const socket = useContext(SocketContext);

  const handleChoose = useCallback(() => {
    const rawMessage: RawMessage = {
      type: MessageType.GAME_CHOOSE,
      message: { word: props.word }
    };
    socket.emit('msg', rawMessage, (response: MessageResponse<undefined>) => {
      if (response.ok) {
        props.setWords([]);
        props.setWordChosen(props.word);
      }
    });
  }, [props.setWordChosen]);

  return (
    <button className={`bg-green-500 active:bg-green-600 fixed
                            text-white font-bold ${'mt-' + 40*(props.index+2)} mt-40
                            px-5 py-2 rounded shadow
                            outline-none focus:outline-none hover:shadow-md
                            ease-linear transition-all duration-100`}
                    type="button"
                    onClick={() => handleChoose()}>{props.word}</button>
  );
}