Overnap

Timer 컴포넌트 추가

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;
};
export 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>
);
}
\ No newline at end of file