How can I update a react hooks state object that has a nested object containing objects with index keys?
Here is the default state object.
const [form, setForm] = useState({
name:'',
price:'',
effects:{
0:{},
1:{},
}
})
My goal is to update the first key in the effects object.
I have tried some code like this.
const variable = "Sleepy"
const variableObject = {[variable]:0}
setForm({...form, ...{...form.effects, ...{0:{ variableObject }} } })
This attempt places the object outside of the nested effects object like this.
{
0:{"Sleepy":0},
1:{},
name:'',
price:'',
effects:{
0:{},
1:{},
}
}
Instead, the final object state should look like this.
{
name:'',
price:'',
effects:{
0:{"Sleepy":0},
1:{},
}
}
How about:
form.effects[0].Sleepy = 0;
setForm({...form});