Reputation: 11435
constructor(){
super();
this.state = {
address: {
street:null,
city:null,
postalCode: null
}
};
}
postalCodeChange(e){
this.setState.address.postalCode = e.target.value;
console.log(this.state);
}
I'm trying to update the state, but the postalCode only. When the above code execute, I expect to get something like this
Object {address: Object {
street: null,
city: null,
postalCode: 'some new value'
} }
But I got error. What's wrong?
Upvotes: 3
Views: 3093
Reputation: 77482
In order to update state you must use setState
method
const state = merge({}, this.state, {
address: { postalCode: e.target.value }
});
this.setState(state);
Note - merge
it is not real function, in order to deep merge objects you can use packages like merge-deep
, assign-deep
or you can use update
method from React.addons
, to get this method do the following steps
npm i react-addons-update --save
import
(or require
) and use it
import update from 'react-addons-update';
const state = update(this.state, {
address: {
postalCode: { $set: e.target.value }
}
});
this.setState(state);
also if you use ES2015
you can use Object.assign
, or spread operator
Object.assign
:
const state = Object.assign({}, this.state, {
address: Object.assign({}, this.state.address, { postalCode: 1000 })
});
spread operator
const newState = {
address: { ...state.address, postalCode: 1000 }
};
Upvotes: 5
Reputation: 689
I saw that you are using ES6, so I'm assuming you can also use the stage-2 object spread operator.
By using that feature, you can update your state without additional plugin or lots of code.
this.setState({
address: {
...this.state.address,
postalCode: e.target.value
}
});
Upvotes: 2