aboutsummaryrefslogtreecommitdiff
path: root/lib/hooks/useCountdownSeconds.ts
diff options
context:
space:
mode:
Diffstat (limited to 'lib/hooks/useCountdownSeconds.ts')
-rw-r--r--lib/hooks/useCountdownSeconds.ts54
1 files changed, 54 insertions, 0 deletions
diff --git a/lib/hooks/useCountdownSeconds.ts b/lib/hooks/useCountdownSeconds.ts
new file mode 100644
index 0000000..3d17ede
--- /dev/null
+++ b/lib/hooks/useCountdownSeconds.ts
@@ -0,0 +1,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 };