Details
Calculating How Much Time is Left
const calculateTimeLeft = () => {
const difference = +new Date("2020-01-01") - +new Date();
let timeLeft = {};
if (difference > 0) {
timeLeft = {
days: Math.floor(difference / (1000 * 60 * 60 * 24)),
hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
minutes: Math.floor((difference / 1000 / 60) % 60),
seconds: Math.floor((difference / 1000) % 60)
};
}
return timeLeft;
};
const difference = +new Date("2020-01-01") - +new Date();
let timeLeft = {};
if (difference > 0) {
timeLeft = {
days: Math.floor(difference / (1000 * 60 * 60 * 24)),
hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
minutes: Math.floor((difference / 1000 / 60) % 60),
seconds: Math.floor((difference / 1000) % 60)
};
}
return timeLeft;
};
Hooking Up the State and Effect
The first line pulls out timeLeft which will carry our time left object of intervals and provide us with a method to set the state. On component load, the timeLeft value is set to the current time left value.
The useEffect line is what updates the amount of time remaining. Every time that timeLeft is updated in the state, the useEffect fires. Every time that fires, we set a timer for 1 second (or 1,000ms) which after that time has elapsed, will update the time left.
The cycle will continue every second thereafter.
The useEffect line is what updates the amount of time remaining. Every time that timeLeft is updated in the state, the useEffect fires. Every time that fires, we set a timer for 1 second (or 1,000ms) which after that time has elapsed, will update the time left.
The cycle will continue every second thereafter.
Displaying the Time Left
Now that we have a working hook that holds the time left as an object, and is being updated every second, now we can build out our display components.
To do so, we’re going to loop through the properties of the timeLeft object and add an element to our components array. Only if the timer interval has a value above zero, that is:
To do so, we’re going to loop through the properties of the timeLeft object and add an element to our components array. Only if the timer interval has a value above zero, that is: