I am having trouble updating my state object that has an array of objects inside. There are few things that I have tried but none of them worked. Here is an example of my state object. With the example below, I want to update the values for test and test2 depending on whatever the user types in input field. Can someone guide me in the right direction. Thank you!
this.state = {
someProperty: {
someOtherProperty: [
object in array: {
test: true,
test2: false
},
object in array: {
test: true
test2: false
}
..
]
...
}
...
}
My attempt on updating the value inside the object is as follows:
this.setState(prevState => ({
...prevState,
someProperty: {
...prevState.someProperty,
someOtherProperty: [
...prevState.someProperty.someOtherProperty,
test: false
]
}
}))
CodePudding user response:
You can create an array latestSomeOtherProperty
, update the wanted index and then;
const latestSomeOtherProperty = someOtherProperty.map(prop=>{...prop, test: false}); // it updates all but you can put condition here
this.setState(prevState => ({
...prevState,
someProperty: {
...prevState.someProperty,
someOtherProperty: [
...latestSomeOtherProperty
]
}
}))