bfrances
bfrances

Reputation: 121

React - setInterval with dynamic prop

I'm a beginner in React. After some research, I don't found a solution for this: I would like to create a down counter with endDate in props and I want to change dynamically the props.

So I wrote this :

import { useState, useEffect } from "react";
import formatSeconds from "../../utils/formatSeconds";
import './down-counter.css';

type Props = {
  endDate: Date
}

const DownCounter = ({ endDate }: Props) => {
  const [timer, setTimer] = useState('');

  useEffect(() => {
    const interval = setInterval(() =>
      setTimer(formatSeconds(diffDate(endDate))), 1000);
    return () => clearInterval(interval)
  }, []);

  const diffDate = (endDate: Date) => {
    return (endDate.getTime() - Date.now()) / 1000;
  };

  return (
    <div className="down-counter">
      {timer} - {endDate.toString()}
    </div>
  )
}

export default DownCounter;

In the parent, when I change the endDate value, this value change in render but not in setInterval.

I would like to know why and how to work around the problem.

Upvotes: 0

Views: 474

Answers (1)

Naveen
Naveen

Reputation: 360

useEffect with an empty dependency array, will run only a single time when the component is mounted. - If you want to render the useEffect on endDate value change , provide as a dependency.

    useEffect(() => {
    const interval = setInterval(() =>
      setTimer(formatSeconds(diffDate(endDate))), 1000);
    return () => clearInterval(interval)
  }, [endDate]);

Upvotes: 1

Related Questions