Sameer Sheikh
Sameer Sheikh

Reputation: 509

ReactJS State not getting updated

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

Upvotes: 2

Views: 113

Answers (2)

Arsh Singh
Arsh Singh

Reputation: 2116

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)
    });
},

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77522

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

Upvotes: 2

Related Questions