Chaitu
Chaitu

Reputation: 135

setState in react is not working in react component

I'm trying to create a small react component, however, I am unable to set the state. Below is my code. In the _onChange function, I am trying to set an array of length 10 to State and console.log the same. I am getting an empty array in the console.

var Home = React.createClass({

    getInitialState: function () {
        return ({
            reviewData: []
        });
    },

    componentWillMount: function() {
        ReviewStore.addChangeListener(this._onChange);
        ReviewAction.getRatings();
        console.log(this.state.reviewData);
    },

    _onChange: function() {
        var res = ReviewStore.getRating();
        console.log(res); //Here I am getting array of length 10
        this.setState({reviewData: ReviewStore.getRating()});
        console.log(this.state.reviewData); //Here I am getting array of length 0
    },

    componentWillUnmount: function () {
        ReviewStore.removeChangeListener(this._onChange);
    },

    ratingChanged : function(newRating) {
        console.log(newRating)
    },

    render: function() {
        return(
            <div>
                <h2>Rating of Arlo Smart Home 1 HD Camera</h2>
                <hr/>
                <h4>Average Rating: </h4><ReactStars half={false} onChange={this.ratingChanged} size={24}/>
            </div>
        )
    }
});

Upvotes: 2

Views: 2128

Answers (1)

Michał
Michał

Reputation: 905

setState is asynchronous. The value will not be set immediately. You can pass a callback to setState which will be called when new state is set.

From react documentation https://facebook.github.io/react/docs/component-api.html

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.

You can change your code

this.setState({reviewData: ReviewStore.getRating()}, function () {
    console.log(this.state.reviewData)
});

Upvotes: 4

Related Questions