Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i change property of nested object in State?

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

like image 314
Maksim Avatar asked Dec 14 '22 10:12

Maksim


1 Answers

Spread the original object and change the property you want:

this.setState(prevState =>({
    ownRecipe : {
        ...prevState.ownRecipe,
        name : 'new name'
    }
}));
like image 53
Dupocas Avatar answered Jan 03 '23 15:01

Dupocas