0

Lets say i have an state and a variable bananas

state = {
    bananas: []
}

And that there is some data in that array, so this means the array isn't empty.

I want to update only one element of the array. I have and index variable with the index that I want to change.

My first try was this:

let newBananas = this.state.bananas
newBananas[index] = value
this.setState({bananas: newBananas })

but I don't think this is good.

I saw this question which helped me a little bit, but my case is different because I don't want to concat or add a new element to the array, I want to modify only one element at a given position.

What is the best way of doing this with good practices?

abiratsis
  • 7,051
  • 3
  • 28
  • 46
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
  • Why don't you think this is a good practice? I do the same thing at work, except I usually make a clone with a spread operator so that it's not mutating the original state variable. – Sterling Archer Mar 18 '19 at 20:54
  • 2
    Yeah, just create a copy of the array first: `let newBananas = [...this.state.bananas];` (or `Array.from(this.state.bananas)`). – Felix Kling Mar 18 '19 at 20:55
  • One thing to note, is that modifying a state variable does *not* trigger a lifecycle update (I found this out the hard way), so I highly suggest creating a copy. Otherwise this is a good react practice because it's clean, and effective. – Sterling Archer Mar 18 '19 at 20:56
  • so a good practice would be create a new array with spread operator? – Vencovsky Mar 18 '19 at 20:57
  • 2
    Good practice is to create a new array without modifying the existing array, the spread operator is one option. – reZach Mar 18 '19 at 20:58
  • 1
    Good practice is to not mutate existing state. That implies creating new objects/arrays when you want to change them. *How* to do that is up to you. – Felix Kling Mar 18 '19 at 20:58

1 Answers1

1

So the best way of doing this would be

let newBananas = [...this.state.bananas]
newBananas[index] = value
this.setState({bananas: newBananas })

Thanks for all the comments!

Vencovsky
  • 28,550
  • 17
  • 109
  • 176