For a plugin I\'m using I have to have a state that looks like this:
getInitialState() {
return {
invalid: true,
access: {
access_code: \'\',
let newAccess = Object.assign({}, this.state.access);
newAccess.hospital_id = 1;
this.setState({access: newAccess});
My preferred way of doing this now is as simple as:
let newAccess = this.state.access;
newAccess.hospital_id = 1;
setState({access: newAccess});
Slightly simpler than the current accepted answer.
EDIT (based on the question from @SILENT )
It looks like this is actually a potentially dangerous method. Further reading here React: A (very brief) talk about immutability.
Looks like a better way to do this would be:
let newAccess = Object.assign({}, this.state.access, {hospital_id:1});
this.setState({access: newAccess});
You have a few options:
With ECMA6, you can use the Object spread proposal (...
) to create copies of objects with updated properties.
this.setState({
access: {
...this.state.access,
hospital_id: 1,
},
});
You can use the native assign function on the Object (Object.assign()
)
this.setState({
access: Object.assign({}, this.state.access, {
hospital_id: 1,
}),
});
Or for the shortest version and atomic update:
this.setState(({access}) => ({access: {
...access,
hospital_id: 1,
}});
And one more option is the updates addon:
var update = require('react-addons-update');
// per React docs
// https://reactjs.org/docs/update.html
// , you may want to change this to
// import update from 'immutability-helper';
this.setState({
access: update(this.state.access, {
hospital_id: {$set: 1},
})
});
I would recommend using the first one.
I had this same issue too(not the same context) anyways, i did the code below in my own work and it worked perfectly
this.setState({
access: {
...this.state.access,
hospital_id: 1,
},
});
Another way to do this would be
const newAccess = {...this.state.access};
newAccess.hospital_id = 1;
setState({access: newAccess});
Use of the spread operator creates a clone of this.state.access
.