I have a state configured in React that is an array of objects:
state = {
metric: [{name: "", type:"", reward: false}],
}
I want the reward attribute to be updated (from false-> true or true->false) when a particular checkbox is checked, which I wrote an onSelectedChange function that uses a particular index in the array as a parameter:
onSelectedChange = (idx) => {
this.setState((prevState) => ({
metric:{
[idx]: {
...prevState.metric[idx],
reward: !prevState.metric[idx].reward
}
}
}))
}
But after this function runs, something must have messed up the state configuration because a later function that uses metric.map(val, idx) fails.
Example of what I expect after the function call:
Before:
state = {
metric: [{name: "latency1", type:"counter", reward: false},
{name: "latency2", type:"counter", reward: false}]
}
After calling onSelectedChange(1):
state = {
metric: [{name: "latency1", type:"counter", reward: false},
{name: "latency2", type:"counter", reward: true}]
}
onSelectedChange(0)