So here is my state:
this.state = {
ids: [\'A\', \'E\', \'C\']
};
How would I go about modifying the state so that \'E\' at index 1 is change
My suggestion is to get used to use immutable operations, so you don't modify internal state object.
As pointed in the react docs:
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
In this case, you can [1] use slice() to get a new copy of the Array, [2] manipulate the copy, and, then, [3] setState with the new Array. It's a good practice.
Something like that:
const newIds = this.state.ids.slice() //copy the array
newIds[1] = 'B' //execute the manipulations
this.setState({ids: newIds}) //set the new state
Case 1: If you know the index then you can write it like this:
let ids = [...this.state.ids]; // create the copy of state array
ids[index] = 'k'; //new value
this.setState({ ids }); //update the value
Case 2: If you don't know the index then first use array.findIndex or any other loop to get the index of item you want to update, after that update the value and use setState.
Like this:
let ids = [...this.state.ids];
let index = ids.findIndex(el => /* condition */);
ids[index] = 'k';
this.setState({ ids });
Here is another solution to change a specific index of array in a setState:
this.setState({
...array,
Object.assign([...array], { [id]: yourNewObjectOrValue })
})
Building on what @mayank-shukla wrote (case 2: knowing the index of the item to replace), this could also be written with Array.splice:
const replacement = 'B';
let copy = [...this.state.ids]
copy.splice(index, 1, replacement)
this.setState({
ids: copy,
})
REPL Example
Two things to note, here:
Array.splice
is mutative; It will change the array it's operating on, but this is a shallow copy of the array because of the spread operator. More on that below. Array.splice
is actually the deleted element(s). AKA: Do not assign the result of your slice to the variable you intend to assign to IDs in setState
, or you will end up with only the deleted value(s).To follow up on shallow vs deep copies from item 1, please note that if you are replacing object references (vs string literals in the question), you will need to use something like lodash's cloneDeep.
There are a handful of other ways around this, though.
You can also read more about shallow vs deep on SO itself.