Hello Developers how are you?
I am trying to update nested values, but all are failing.
const [ControlGaps, setControlGaps] = useState([
{
id: 1,
name: "Pizza 1",
status: 1,
applicable: true,
questions: [
{
id: 1,
question:
"how are you?",
answer: null,
evidence: null,
treatment: null,
type: "Implemented",
{
id: 2,
evidence: null,
treatment: null,
type: "Implemented",
question:
"how old are you?",
answer: null,
}
],
},
{
id: 2,
name: "Pizza 2",
status: 1,
applicable: true,
questions: [
{
id: 1,
type: "Implemented",
question:
"How are you 2?",
answer: null,
evidence: null,
treatment: null,
{
id: 2,
answer: null,
evidence: null,
treatment: null,
type: "Implemented",
question:
"How old are you?",
},
],
}])
I tried to use onChange this
setControlGaps([...ControlGaps, [ControlGaps[index]].applicable]:checked]);
or
setControlGaps({
...ControlGaps,
[ControlGaps[index].applicable]: checked,
});
But it's all wrong.
The question is how to update values in nested field like updating fields in object inside array of objects for example.
Can be done using some slice()
and spread
. But you should look at immutability helpers for such nested stuff.
setControlGaps([setControlGaps.slice(0,index),
{ ...ControlGaps[index],
applicable : checked
}
,setControlGaps.slice(index+1)]);
Try this
setControlGaps(prevState => {
const newState = prevState.map((item, itemIndex) => {
if (itemIndex === index) {
item.applicable = false;
return item;
}
return item;
});
return newState;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.