2

I am updating a state from child.

getInitialState : function(){
        return{
            VotedForTopic : false

        };
    },

updateVotedState:function(){
        this.setState({VotedForTopic:true});
        console.log(this.state.VotedForTopic)
    },

I am calling updateVotedState from the child when some action is performed to change the VotedForTopic state to true.But the state is not getting updated it remains false. What could be the problem

1
  • 1
    this.setState(newState) is async. it happens very fast, but you can move the console.log into your render method and you'll see it update. Commented Jan 1, 2016 at 3:24

2 Answers 2

2

You can update parent state from child using callback which passed to child through props, like this

var Parent = React.createClass({
    getInitialState: function () {
        return {
            VotedForTopic: false
        };
    },

    updateVotedState: function () {
        this.setState({ VotedForTopic: true });
    },

    render: function() {
        return <div>
            <p>{'Current State:: ' + this.state.VotedForTopic} </p>
            <Child onUpdateVote={this.updateVotedState} />
        </div>;
    }
});

var Child = React.createClass({
    render: function() {
        return <a onClick={this.props.onUpdateVote}>updateVotedState</a>;
    }
});

Example

0
1

Does the state never update or are you relying on the console.log ? From the docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

try passing a callback to setState:

updateVotedState:function(){
    var that = this;
    this.setState({VotedForTopic:true}, function(){
        console.log(that.state.VotedForTopic)
    });
},
1
  • this will show as true.. but then when i click on an item which checks the value of VotedForTopic before doing some action shows the value as false. Commented Oct 23, 2015 at 8:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.