Hey guys help me to done with this, I have an state like this :
this.state = {arr:[1,2,3]}
How to push a new value to that array of state, for example I want to push this value : addArr = [4,5,6]
Hey guys help me to done with this, I have an state like this :
this.state = {arr:[1,2,3]}
How to push a new value to that array of state, for example I want to push this value : addArr = [4,5,6]
You can accomplish this with destructuring
this.setState(
(state) => ({
arr: [...state.arr, x]
})
);
x will be inserted. It sounds like your value may have been out of scopesetState doesn't actually update the state immediately. It would be better to use the for loop to generate the data first, then insert that data after.You should never edit directly the state object as this.state.arr.push(...), instead you should you should replace entirely the state with this.setState(...) being a pure function.
In this case you can
this.setState({arr: [...state.arr, addArr]})
setState lambda instead of relying on this.state as it may have changed by the time you get to running setState.