Added a useCountDown hook to handle countdown

This commit is contained in:
Moon Patel
2023-07-05 16:14:11 +05:30
parent 5dbf0409f6
commit a7a1d08b46
2 changed files with 29 additions and 0 deletions
+1
View File
@@ -22,6 +22,7 @@ import ChessGame from './pages/Chess/ChessGame'
import JoinChallenge from './components/JoinChallenge'
import ErrorBoundary from './components/ErrorBoundary'
import ChessGameContextProvider, { ChessGameContext } from './context/chess-game-context'
import useCountDown from './hooks/useCountDown'
const router = createBrowserRouter([{
path: '/',
+28
View File
@@ -0,0 +1,28 @@
import React, { useEffect, useState } from 'react'
const useCountDown = (timeLimit) => {
const [timeLeft, setTimeLeft] = useState(timeLimit * 60 * 1000);
useEffect(() => {
if (timeLeft > 0) {
const interval = setInterval(() => {
setTimeLeft((prev) => prev - 1000);
}, 1000);
return () => {
clearInterval(interval)
}
}
}, [timeLeft]);
return getFormattedTime(timeLeft)
}
function getFormattedTime(time) {
let minutes = Math.floor(time / (1000 * 60));
let seconds = Math.floor(time / (1000)) % 60;
return [seconds, minutes];
}
export default useCountDown