Timer.tsx
1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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>
);
}