state looks like this for example
{
ownRecipe: {name:""}
}
now i need to change name property, this doesn't work
this.setState({ownRecipe[name]:"Pineapple pizza"});
this works, but maybe there is a better way?
let ownRecipeCopy = {}
for(let key in this.state.ownRecipe){
ownRecipeCopy[key] = this.state.ownRecipe[key];
}
ownRecipeCopy.name = e.target.value;
this.setState({ownRecipe: ownRecipeCopy});
Edit: thanks everyone for your answers
Spread the original object and change the property you want:
this.setState(prevState =>({
ownRecipe : {
...prevState.ownRecipe,
name : 'new name'
}
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With