Timer.tsx 1.25 KB
import React, { useCallback, useContext, useEffect, useState } from 'react';
import SocketContext from '../../contexts/SocketContext';
import { MessageType, RawMessage } from '../common/types';

interface timer {
  state: "started" | "stopped";
  time: number;
};

const Timer: React.FC = () => {
  const socket = useContext(SocketContext);

  const [ time, setTime ] = useState(0);
  const [ isStop, setIsStop ] = useState(true);

  const handleTimeSet = useCallback((rawMessage: RawMessage) => {
    if (rawMessage.type === MessageType.GAME_TIMER) {
      const data = rawMessage.message as timer;
      
      console.log(data);
      if (data.state === 'started') {
        setIsStop(false);
      } else {
        setIsStop(true);
      }

      setTime(Math.floor(data.time));
    }
  }, []);

  useEffect(() => {
    if (!isStop) {
      const go = setInterval(() => {
        setTime(time-1);
      }, 1000);

      return () => clearInterval(go);
    } else {
      setTime(0);
    }
  }, [time, isStop]);

  useEffect(() => {
    socket.on('msg', handleTimeSet);
    return () => {
      socket.off('msg', handleTimeSet);
    }
  }, []);

  return (
    <div className={time < 10 ? 'text-red-500' : 'text-black'}>
      🕒 {time}
    </div>
  );
}

export default Timer;