Reputation: 113
I'm defining my state in constructor like this.
constructor(props) {
super(props);
this.state = {
order: props.data ? { ...props.data } : { title: '', birthdate: '' , gender: '', startdate: '', starttime: '', brand: null},
Then in another function i'm trying to setState only for order.brand
this.setState({
//order: { brand: items[0].title },
order: { ...order, brand: items[0].title },
});
The commented line is overwriting all elements, and the second returns that order is not defined.
What's the correct syntax to save just one item of the state that have multiple values.
Upvotes: 4
Views: 3141
Reputation: 32392
As mentioned in the comments you can use update
to modify object values:
var update = require('react-addons-update');
this.setState(function(previousState, currentProps) {
var newState = update(previousState,{
order: {
brand: {
$set: 'some new value'
}
}
});
return newState;
});
see https://facebook.github.io/react/docs/update.html
Upvotes: 1
Reputation: 840
Just to note why that error exists, it's possible that order is actually undefined where you are using it.
You're liking trying to use {...this.state.order}
Upvotes: 0