Issue with setting State with setInterval and clearInterval

  asynchronous, javascript, reactjs, state

I’ve found unexpected behaviour from react when trying to update state from an function being called at intervals by setInterval(). The aim is to have a Button that invokes a setInterval that calls a function that requests data from my MySQL database, then sets the first array of results to my State. I want that same button to also clear the interval when pressed again. On and on.

I’ve Noticed that the Code works fine if you comment out the setData function. I was hoping someone could explain why the code works as expected until you try setting state with the setInterval Function.

      const getData = async () => {
        const lastEntry = await API.getLastEntry("rig08");
        console.log(lastEntry);
        setData(lastEntry[0] || 0);
      }

      var dataUpdate = null;
      const toggleLive = async () => {
        console.log(dataUpdate);
        if (!dataUpdate) {
          console.log("Condition");
          dataUpdate = setInterval(getData, 1000);
        } else {
          console.log("Else");
          clearInterval(dataUpdate);
          dataUpdate = null;
        }
      }

I’m guessing it’s got something to do with the react state not updating straight away or maybe even it’s got something to do with aysnc? Hopefully someone has a better understanding of what’s going on.

Source: Ask Javascript Questions

LEAVE A COMMENT