Reputation: 1147
I have this snippet that doesn't seem to be work and it is driving me insane! Can someone please point out what I have done wrong ?
getInitialState: function () {
return {
modalUser: {},
users: []
};
},
updateModalUser: function (user) {
console.log(user);
module.React.addons.update(this.state, {
modalUser: { $set: user }
});
console.log(this.state);
},
I did try doing this originally without the addons, but I had the same result. i.e. my updateModalUser looked like:
updateModalUser: function (user) {
console.log(user);
this.setState({
modalUser: user
});
console.log(this.state);
},
This output I get either way is:
Object {id: 28, fname:"fred", lname:"flinstone"…}
Object {modalUser: {}, users: []}
Upvotes: 0
Views: 1298
Reputation: 108520
this.setState()
is async, you need to log the state in it’s callback:
updateModalUser: function (user) {
console.log(user);
this.setState({
modalUser: user
}, function() {
console.log(this.state);
})
}
More info here: https://facebook.github.io/react/docs/component-api.html#setstate
Upvotes: 3
Reputation: 18922
You should use this.setState({modalUser: newObjectHere})
, which is the correct way of altering a component's state.
Upvotes: -1