Reputation: 237
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]
Upvotes: 0
Views: 75
Reputation: 99
using the useState()
this should always work:
var [firstArray, setFirstArray] = useState([1, 2, 3]);
var secondArray = [4, 5, 6]
const fun = () => {
setFirstArray((e) => [...e, ...secondArray])
}
fun()
as e
representing the old value of firstArray
Upvotes: 0
Reputation: 888
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]})
Upvotes: 1
Reputation: 1386
You can accomplish this with destructuring
this.setState(
(state) => ({
arr: [...state.arr, x]
})
);
Upvotes: 2