1

I have initial state for the current value of multiple <Switch /> components contained inside a <SectionList /> as follows:

this.state = {
  switchValues:[
    [true],
    [false, true], //i want to amend 'true' to be 'false'
    [false],
  ],
};

How do I update the item at switchValues[1][1] to be false using setState?

There are other answers to similar questions such as this but the question relates to nested objects rather than arrays

Taking what I can from the linked answer I came up with

this.setState(
  {
    switchValues: [...this.state.switchValues,
                   [section][index]: value,
    ],
  }
);

where both section and index are the correct int values for the position in the array, but that doesn't update the correct element in the array.

Is this possible?

Chris
  • 4,662
  • 2
  • 19
  • 27

1 Answers1

2

The way you have it, [section][index] are not referencing anything. You would need something like array[section][index]. Also, using the spread operator will pull in the whole array again, which is fine, but then it's like you are pushing another 'section' into the array as well. This should work:

// make a copy of the array since you can't mutate state
let copyValues = this.state.switchValues.slice();
// make the changes to the copied array
copyValues[section][index] = value //false or whatever

// set state
this.setState({
  switchValues: copyValues
})

I think this is what you want.

Jordan
  • 148
  • 1
  • 11