0

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: []}
0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! that worked!... I tried wrapping console.log(this.state) within a setTimeout 2000, but that can't have been long enough!
-1

You should use this.setState({modalUser: newObjectHere}), which is the correct way of altering a component's state.

1 Comment

That is what I did. I have edited the example above to try and point this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.