frederix
frederix

Reputation: 1832

Reactjs prop available in render but not in componentDidMount

I'm having a weird issue. When I call "UserShowStatsSuggestions" from this class:

var UserShowStatsPanelBody = React.createClass({
    getInitialState: function() {
        return {data: []};
    },
    componentDidMount: function() {
        // Get the show
        var showUrl = "/api/v1/show/" + this.props.showStats.show + "/";
        $.ajax({
            url: showUrl,
            dataType: 'json',
            success: function(data) {
                this.setState({data: data});
            }.bind(this),
            error: function(xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },
    render: function() {
        var statElements = [];
        // Create the user show stats
        if (this.props.showStats) {
            var showID = this.state.data.id;
            var showLink = "/leaderboards/show/" + showID + "/";
            var recapLink = "/recap/" + this.state.data.id + "/";
            statElements.push(<div className="row"></div>);
            statElements.push(<div className="row"></div>);
            statElements.push(<div className="row"></div>);
            statElements.push(<UserShowStatsSuggestions userID={this.props.userID} showID={showID} />);
            statElements.push(<div className="row"></div>);
        }

        return (
            <div>{statElements}</div>
        );
    }
});

I can access the prop "showID" in render, but not in componentDidMount:

var UserShowStatsSuggestions = React.createClass({
    getInitialState: function() {
        return {data: []};
    },
    componentDidMount: function() {
        console.log(this.props);
    },
    render: function() {
        console.log(this.props);
        return (
            <div></div>
        );
    }
});

From componentDidMount console.log:

{userID: "107050829081899378766", showID: undefined}

From render console.log

{userID: "107050829081899378766", showID: 5705241014042624}

Any ideas why this would be the case?

Upvotes: 4

Views: 10127

Answers (1)

Silfverstrom
Silfverstrom

Reputation: 29322

Look if the console.log in render is executed more than once.

componentDidMount only runs once, so you will never see another console.log executed with the correct showID in componentDidMount.

However, render runs more than once, so you would see the console.log after the parents state has been updated, where showId no longer is null.

Modify your parents render method to not render before your ajax call has been completed.

Upvotes: 6

Related Questions