Search code examples
arraysreactjsreact-nativestatenative

updating one value in State array react native


Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state

This is essentially what I have

this.state = { array: ['a', 'b', 'c'] };

onBack() {
  this.setState({
      array[2]: 'something' 
  });
}

Solution

  • You can't update the state like this.

    Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

    Read React docs.

    You can do something like this :

    let newArray = [...this.state.array];
    newArray[2] = 'somethingElse';
    this.setState({array: newArray});
    

    The above example is using Spread Syntax.

    There are multiple ways to modify state, but all the ways should ensure that data is treated as immutable. You can read more about handling state in React here