This is a simplified version of a problem I've faced while working in React. When I'm making a fetch call inside componentDidMount()
and updating the state with the payload as follows:
componentDidMount(){
fetch("/api/endpoint").then(data => {
return data.json();
}).then(json => {
this.setState({
data: json
});
});
}
And rendering it out in render()
:
render(){
return(
<p>{this.state.data.title}</p>
)
}
I get an error saying this.state.data is undefined
. I got around it by wrapping it around a conditional operator as follows:
{ this.state.data !== undefined ? <p>{this.state.data.title}</p> : null }
But my question is, if componentDidMount()
fires before render()
then how can this.state.data
ever be undefined?