diff options
Diffstat (limited to 'utils/useCountdownSeconds.js')
| -rw-r--r-- | utils/useCountdownSeconds.js | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/utils/useCountdownSeconds.js b/utils/useCountdownSeconds.js new file mode 100644 index 0000000..df3cb63 --- /dev/null +++ b/utils/useCountdownSeconds.js @@ -0,0 +1,37 @@ +import { useEffect, useState } from "react"; + +const useCountdown = (targetDate, update) => { + const countDownDate = new Date(targetDate).getTime(); + + const [countDown, setCountDown] = useState( + countDownDate - new Date().getTime() + ); + + useEffect(() => { + const interval = setInterval(() => { + const newCountDown = countDownDate - new Date().getTime(); + setCountDown(newCountDown); + if (newCountDown <= 0 && newCountDown > -1000) { + update(); + } + }, 1000); + + return () => clearInterval(interval); + }, [countDownDate, update]); + + return getReturnValues(countDown); +}; + +const getReturnValues = (countDown) => { + // calculate time left + const days = Math.floor(countDown / (1000 * 60 * 60 * 24)); + const hours = Math.floor( + (countDown % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60) + ); + const minutes = Math.floor((countDown % (1000 * 60 * 60)) / (1000 * 60)); + const seconds = Math.floor((countDown % (1000 * 60)) / 1000); + + return [days, hours, minutes, seconds]; +}; + +export { useCountdown }; |