add useCountdown

This commit is contained in:
Dawid Wysokiński 2021-03-27 08:32:34 +01:00
parent 7915f1041a
commit abeb17b796
2 changed files with 40 additions and 0 deletions

1
src/libs/hooks/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './useCountdown';

View File

@ -0,0 +1,39 @@
import { useEffect, useState } from 'react';
export type DifferenceBetweenDates = {
days: number;
hours: number;
minutes: number;
seconds: number;
};
const calculateDifference = (
dateLeft: Date,
dateRight: Date
): DifferenceBetweenDates => {
const difference = dateRight.getTime() - dateLeft.getTime();
return {
days: difference > 0 ? Math.floor(difference / (1000 * 60 * 60 * 24)) : 0,
hours:
difference > 0 ? Math.floor((difference / (1000 * 60 * 60)) % 24) : 0,
minutes: difference ? Math.floor((difference / 1000 / 60) % 60) : 0,
seconds: difference ? Math.floor((difference / 1000) % 60) : 0,
};
};
export const useCountdown = (dateRight: Date): DifferenceBetweenDates => {
const [difference, setDifference] = useState<DifferenceBetweenDates>(
calculateDifference(new Date(), dateRight)
);
useEffect(() => {
const timeout = setTimeout(() => {
setDifference(calculateDifference(new Date(), dateRight));
}, 1000);
return () => {
clearTimeout(timeout);
};
}, [dateRight]);
return difference;
};