Correct way to push into state array

Ilja picture Ilja · May 25, 2016 · Viewed 276.3k times · Source

I seem to be having issues pushing data into a state array. I am trying to achieve it this way:

this.setState({ myArray: this.state.myArray.push('new value') })

But I believe this is incorrect way and causes issues with mutability?

Answer

Aliaksandr Sushkevich picture Aliaksandr Sushkevich · Mar 24, 2017

Using es6 it can be done like this:

this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array

Spread syntax