Ahmad Al-kheat
Ahmad Al-kheat

Reputation: 1795

React component being rendered with old props

I have the following component:

var Answer = React.createClass({

  getInitialState: function(){
    return {edit: false, comments: []}
  },

componentWillMount: function(){
    $.ajax({
        context: this,
        method: 'GET',
        url: '/answers/' + this.props.answer.id + '/comments/',
        success: function(data){
            this.setState({comments: data});

        }
    });
},

render: function(){
    return ( 
        <div>
             //This renders with initial comments in the state, the empty array
            <Comments comments={this.state.comments} /> 
        </div>
    );
},

notice how I fetch comments from the server and save them into state then pass them as props to comments. Problem is the props are being passed as the old state, not the new state that's fetched from the server. What am I missing here?

Upvotes: 1

Views: 3561

Answers (1)

Ahmad Al-kheat
Ahmad Al-kheat

Reputation: 1795

Alright I figured it out after some thought. The problem was that render is being called before componentWillMount, so the child component Comments was being rendered with the initial props the first time, so I needed to let the child component know that it will receive new props when the parent set its state. I added this code to my child component:

componentWillReceiveProps: function(newProps){
        this.setState({comments: newProps.comments})
    },

Upvotes: 2

Related Questions