1

I'm trying to display difference in two dates and display in my component, originally I set interval for 60 seconds but now I have one sec for debugging and clearly it doesn't want to update the state. Idea is to launch it once at start and then tick every 60 sec.

  const calculateTimeDifference = () => {
    const currentDate = dayjs()
    const reservationFinishDate = dayjs('2023-03-30T11:00:00.000Z')
    const diff = reservationFinishDate.diff(currentDate, 'minutes', true)
    const hours = Math.floor(diff / 60)
    const minutes = (dayjs().minute(diff) as any).$m
    setDuration(`${hours}h ${minutes}m`)
  }

  useEffect(() => {
    calculateTimeDifference()
    const interval = setInterval(calculateTimeDifference, 1000)

    return () => clearInterval(interval)
  }, [duration])
Jacki
  • 632
  • 3
  • 14
  • 26
  • Does this help? https://stackoverflow.com/questions/53024496/state-not-updating-when-using-react-state-hook-within-setinterval – Kypps Mar 30 '23 at 10:50

1 Answers1

2

This answer is inpired by the useInterval hook (which may be a solution):

const calculateTimeDifference = () => {
  const currentDate = dayjs();
  const reservationFinishDate = dayjs("2023-03-30T11:00:00.000Z");
  const diff = reservationFinishDate.diff(currentDate, "minutes", true);
  const hours = Math.floor(diff / 60);
  const minutes = (dayjs().minute(diff) as any).$m;
  setDuration(`${hours}h ${minutes}m`);
};

const savedFunction = useRef(calculateTimeDifference);

useEffect(() => {
  const id = setInterval(() => savedFunction.current(), 1000);

  return () => clearInterval(id);
}, []);
devpolo
  • 2,487
  • 3
  • 12
  • 28