aboutsummaryrefslogtreecommitdiff
path: root/lib/hooks/useCountdownSeconds.ts
blob: 3d17ededea1a466554a9553a40033137e00e5c73 (plain) (blame)
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
import { useEffect, useState } from "react";

interface CountdownValues {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
}

interface Props {
  targetDate: number;
  update: Function;
  countdown: CountdownValues;
}

const useCountdown = (targetDate: number, update: Function): Props => {
  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 {
    targetDate,
    update,
    countdown: getReturnValues(countDown),
  };
};

const getReturnValues = (countDown: number): CountdownValues => {
  // 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 };