React: unable to fetch state inside setInterval

I have a button on which I need to call a setInterval but if the interval is already set then I don’t want to initiate another setInterval.

So this is how I have implemented it ():

export default function App() {
  const [intervalId, setIntervalId] = useState(null);

  const startInterval = () => {
    console.log("inside startInterval", intervalId);
    if (!intervalId) {
      console.log("starting Interval", intervalId);
      const _intervalId = setInterval(() => {
        console.log("Interval Id inside setInterval is", intervalId);
      }, 2 * 1000);
      setIntervalId(_intervalId);
    } else {
      console.log("Rejecting set interval");
    }
  };

  const onBtnClick = () => {
    console.log("btn clicked");
    // make API call
    startInterval();
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={onBtnClick}>Click Me</button>
    </div>
  );
}

but inside setInterval I always get to see the default value of state i.e. null in my case.
How can I access the latest value inside setInterval?

Click here to go to Live Code Sandbox

17 thoughts on “React: unable to fetch state inside setInterval”

  1. 756482 546600Greetings! This really is my initial comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading by means of your blog posts. Can you recommend any other blogs/websites/forums that deal with the same topics? Thank you so considerably! 887449

    Reply

Leave a Comment