mikeriley131 mikeriley131 - 1 year ago 122
React JSX Question

React: Getting props to load on initial render

comes from an AJAX request in the parent component. If I comment out
console.log('stageID', currentStage._id);
, this component currently loads 3 times before I finally get the data. When that log is uncommented, it throws an
Uncaught TypeError: Cannot read property '_id' of undefined
, because I don't yet have the data.

How can I get this data to load on initial render?

export default class NavMain extends React.Component {
constructor(props) {

this.state = {
stagesData: []
componentWillMount() {
var stagesData = this.props.allStagesData;

stagesData: stagesData
render() {
var stagesData = this.state.stagesData,
currentStage = _.find(stagesData, {'_status': "open"});

console.log('this.props.allStagesData', this.props.allStagesData);
console.log('this.state.stagesData', stagesData);
console.log('currentStage', currentStage);
console.log('stageID', currentStage._id);

return (


(Disregard the two errors in the image, they are unrelated.)

Answer Source

Before your data is there, you can simply return something else, or null. Try adding if(this.state.stagesData.length === 0) return null to the first line of your render function. That way it will not display until the data is actually there.

Edit: To answer your question, the data can't be there on the first render. A better way to do this would be to return the HTML that has everything except your data, or simply null as stated above, until the request is finished. You can also render a loading indicator if you want!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download