Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to add a value to an array in state

I have an array in state, let's say this.state.arr. I want to add something to this state property, and then change some more properties.

Option 1

onChange(event){     this.state.arr.push('newvalue');     ...     this.setState({some:'val',arr:this.state.arr}) } 

Option 2

onChange(event){     var newArr = this.state.arr;     ...     newArr.push('newvalue');     ...     this.setState({some:'val',arr:newArr}) } 

So.. I know this.state is supposed to be treated immutable. But is it ok to use it like in option 1 where I still set the state from it, or do I need to go with something like option 2, and thus always first making a copy in memory

like image 883
Flion Avatar asked Oct 22 '14 10:10

Flion


People also ask

How do you add a value to an array in React?

Use the spread syntax to push an element into a state array in React, e.g. setNames(current => [... current, 'Carl']) . The spread syntax (...) will unpack the existing elements of the state array into a new array where we can add other elements.

How do you add values to an existing array?

JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array.


1 Answers

For now, this is the best way.

this.setState(previousState => ({     myArray: [...previousState.myArray, 'new value'] })); 
like image 87
Kutsan Kaplan Avatar answered Oct 13 '22 04:10

Kutsan Kaplan