kennet postigo kennet postigo - 8 days ago 4
React JSX Question

componentDidMount() not being called when react component is mounted

I've been attempting to fetch some data from a server and for some odd reason

componentDidMount()
is not firing as it should be. I added a
console.log()
statement inside of
componentDidMount()
to check if it was firing. I know the request to the server works as it should As I used it outside of react and it worked as it should.

class App extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
obj: {}
};
};

getAllStarShips () {
reachGraphQL('http://localhost:4000/', `{
allStarships(first: 7) {
edges {
node {
id
name
model
costInCredits
pilotConnection {
edges {
node {
...pilotFragment
}
}
}
}
}
}
}
fragment pilotFragment on Person {
name
homeworld { name }
}`, {}). then((data) => {
console.log('getALL:', JSON.stringify(data, null, 2))
this.setState({
obj: data
});
});
}

componentDidMount() {
console.log('Check to see if firing')
this.getAllStarShips();
}

render() {
console.log('state:',JSON.stringify(this.state.obj, null, 2));
return (
<div>
<h1>React-Reach!</h1>
<p>{this.state.obj.allStarships.edges[1].node.name}</p>
</div>
);
}

}

render(
<App></App>,
document.getElementById('app')
);

Answer

The issue here is that the render method is crashing, because the following line is generating an error

<p>{this.state.obj.allStarships.edges[1].node.name}</p>

Fix this to not use this.state.obj.allStarships.edges[1].node.name directly, unless you can guarantee that each receiver is defined.