Reputation: 1
When I try to access a state variable which is set in ComponentDidMount
, react throws an undefined error. This is because I believe when I'm calling the fetch api
and setState
in ComponentDidMount
, the value isn't ready yet (async
stuff). Is there a proper way to either delay the render until the setState
call is done or some other way to get the state updated fully before render is called?
Upvotes: 0
Views: 436
Reputation: 3370
I think the code below will give you a basic idea how fetch data and render work.
class App extends Component {
state = {
data:{},
loading:true,
error:null,
}
componentDidMount = () => {
fetch('https://example.com/api/article')
.then((response) => {
return response.json();
})
.then((json) => {
this.setState({
data:json,
loading:false,
})
.catch(error => {
this.setState({
error,
loading:false,
})
});
});
}
render() {
const {data,error,loading} = this.state;
if(loading){
return "Loading ..."
}
if(error){
return "Something went wrong."
}
return 'your actual render component or data';
}
}
export default App;
Upvotes: 1