iMMuNiTy
iMMuNiTy

Reputation: 476

keep default state's values if it's missing in new state React

I want the state to keep all the properties even if the new state doesn't have some. Is it possible with easy fast way?

this.state={
fruits:['apple','orange'],
hungry:false,
drinks:{ alchohol:false, diary:false }
}
var newState= {
fruits:['apple','orange'],
hungry:false,
}

  // new state
this.setState({...newState});
i get state
{    
 fruits:['apple','orange'],
 hungry:false,
}
but i want
{    
 fruits:['apple','orange'],
 hungry:false,
 drinks:{ alchohol:false, diary:false },
}

Upvotes: 0

Views: 41

Answers (2)

Rick
Rick

Reputation: 997

This should do it:

this.state = { thing: ‘foo’, otherThing: 1 };
const newState = { otherThing: 5 };
this.setState(Object.assign({}, this.state, newState));

The state will be { thing: ‘foo’, otherThing: 5 } on completion

It’ll overwrite the old state with properties in the new. Any that don’t exist in the new will have the old value.

Upvotes: 0

h-des
h-des

Reputation: 865

Try this when defining new state

var newState= {
...this.state,
fruits:['apple','orange'],
hungry:false,
}

Upvotes: 1

Related Questions