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?
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 --saveimport(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);
Example
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 }
};
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
}
});
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