updating one value in State array react native
Solution 1
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
Solution 2
Manoj's answer will work, there is another way using the updater function (funtinal setState
) for setState
(which you can read about here)
onBack() {
this.setState(prevState => {
let newArray = prevState.array
newArray[2] = "something"
return { array: newArray }
});
}
Red
Updated on June 04, 2022Comments
-
Red almost 2 years
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' }); }
-
bamtheboozle almost 6 yearsThis is wrong as it mutates the state directly.
arr = this.state.array
does NOT behave as you expect it to. -
Kirankumar Dafda almost 6 yearsI have tried to with my own demo project and its working fine as OP wants.
-
bamtheboozle almost 6 yearsBecause this is fundamentally wrong and shouldn't be the accepted answer.
arr = this.state.array
does not create a new array, but creates a reference tostate.array
. Try console loggingthis.state.array
after you doarr[2] = "something"
and see what happens. -
bamtheboozle almost 6 yearsYou clearly don't understand immutability and what I'm trying to explain so I'm just going to stop.
-
Kirankumar Dafda almost 6 yearsSorry for that, and thanks for clearing the concept of immutable state, I google it and tried to understand the same.
-
kojow7 over 5 yearsWhen you do
arr[2]
you are directly modifying what is in state. This is not a good idea to do. Also, because you are directly modifying state, there is little point of usingsetState
as the state has already been changed in the previous step. -
GD- Ganesh Deshmukh almost 4 yearsupvoted for spread-operator approach, also just for extra knowledge, which will be better for performance direct mutation of state or using spread-operator?
-
illiteratewriter almost 4 yearsmutating directly would be faster since you don't have to create a copy, but that would result in an inconsistent state and is something that should never be done. The spread operator basically creates a copy of the original array.