6

I am trying to update the value of stateValue with the value of i in setInterval but it changes only the value of i and doesn't update the stateValue in setInterval.

fun1 = () => {
  let i = 0;
  let intervalId = setInterval(() => {
    console.log("i:", i);
    this.setState({
      stateValue: i
    });

    i = i + 1;
    if (i === 3) {
      i = 0;
    }
    console.log("stateValue:", this.state.stateValue);
  }, 5000);
};
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Dheeraj Kumar
  • 119
  • 2
  • 12
  • check this . https://stackoverflow.com/questions/47385492/react-how-to-add-new-element-in-array-type-state?answertab=active#tab-top – Dhaval Nov 24 '17 at 04:18
  • setState is an asynchronous method. That means right after writing setState, you cannot expect the state to be changed immediately – Dhaval Nov 24 '17 at 04:18

1 Answers1

4

FROM DOC :

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

You should use this to get the immidiate state update value:

this.setState({
    stateValue: i
},() => {
    console.log("stateValue:", this.state.stateValue);
});
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122