Overnap

Timer 컴포넌트 추가

1 +import React, { useCallback, useContext, useEffect, useState } from 'react';
2 +import SocketContext from '../../contexts/SocketContext';
3 +import { MessageType, RawMessage } from '../common/types';
4 +
5 +interface timer {
6 + state: "started" | "stopped";
7 + time: number;
8 +};
9 +
10 +export const Timer: React.FC = () => {
11 + const socket = useContext(SocketContext);
12 +
13 + const [ time, setTime ] = useState(0);
14 + const [ isStop, setIsStop ] = useState(true);
15 +
16 + const handleTimeSet = useCallback((rawMessage: RawMessage) => {
17 + if (rawMessage.type === MessageType.GAME_TIMER) {
18 + const data = rawMessage.message as timer;
19 +
20 + console.log(data);
21 + if (data.state === 'started') {
22 + setIsStop(false);
23 + } else {
24 + setIsStop(true);
25 + }
26 +
27 + setTime(Math.floor(data.time));
28 + }
29 + }, []);
30 +
31 + useEffect(() => {
32 + if (!isStop) {
33 + const go = setInterval(() => {
34 + setTime(time-1);
35 + }, 1000);
36 +
37 + return () => clearInterval(go);
38 + } else {
39 + setTime(0);
40 + }
41 + }, [time, isStop]);
42 +
43 + useEffect(() => {
44 + socket.on('msg', handleTimeSet);
45 + return () => {
46 + socket.off('msg', handleTimeSet);
47 + }
48 + }, []);
49 +
50 + return (
51 + <div className={time < 10 ? 'text-red-500' : 'text-black'}>
52 + 🕒 {time}
53 + </div>
54 + );
55 +}
...\ No newline at end of file ...\ No newline at end of file