I am getting the property endDate from a redux store and I am sure that the property is not null or undefined, but then again the state keeps it's previous displayed value until the page is refreshed. I want the page to automatically set the state of timeLeft to millisecondsToTime(now, endDate) by default, but currently it fails, despite working after reload.
import React, { FC, useEffect, useState } from "react";
import { millisecondsToTime } from "src/utils/helpers";
import {
StyledCountdownTimer,
StyledTimeBox,
StyledTimeBoxNumbers,
StyledTimeBoxText
} from "./StyledCountdownTimer";
import { getActiveCampaign } from "../../reduxStore";
export interface CountdownTimerProps {
endDate?: string;
}
const CountdownTimer: FC<CountdownTimerProps> = ({ endDate }) => {
const now = Date.now();
const [timeLeft, setTimeLeft] = useState(millisecondsToTime(now, endDate));
const data = getActiveCampaign();
console.log(data);
useEffect(() => {
const timer = setTimeout(() => {
setTimeLeft(millisecondsToTime(now, endDate));
}, 1000);
if (timeLeft.finished) {
clearTimeout(timer);
}
return () => {
clearTimeout(timer);
};
}, [endDate, now, timeLeft.finished]);
return (
<StyledCountdownTimer>
{endDate}
{timeLeft.days}
{millisecondsToTime(now, endDate).days}
<StyledTimeBox>
<StyledTimeBoxNumbers>{timeLeft.days}</StyledTimeBoxNumbers>
<StyledTimeBoxText>Days</StyledTimeBoxText>
</StyledTimeBox>
<StyledTimeBox>
<StyledTimeBoxNumbers>{timeLeft.hours}</StyledTimeBoxNumbers>
<StyledTimeBoxText>Hours</StyledTimeBoxText>
</StyledTimeBox>
<StyledTimeBox>
<StyledTimeBoxNumbers>{timeLeft.minutes}</StyledTimeBoxNumbers>
<StyledTimeBoxText></StyledTimeBoxText>
</StyledTimeBox>
<StyledTimeBox>
<StyledTimeBoxNumbers>{timeLeft.seconds}</StyledTimeBoxNumbers>
<StyledTimeBoxText>Seconds</StyledTimeBoxText>
</StyledTimeBox>
</StyledCountdownTimer>
);
};
export { CountdownTimer };