Reputation: 80
I am designing a covid19 watcher application using an open source API. I log out the state to see if it updates, which it does, but when I pass the state to a component, it doesn't get the data passed.
So I put in a condition on the render() and it seems the state doesn't update so the component doesn't get it. Maybe because componentDidMount runs after render has. How do I fix it?
App.js
import React from 'react';
import Homepage from './pages/homepage/homepage.component.jsx';
import './App.css';
class App extends React.Component{
constructor(){
super()
this.state = {
statistics:{},
}
}
componentDidMount(){
fetch('https://api.covid19api.com/summary')
.then(response => response.json())
.then(data => {
const all_data = data;
this.setState({statistics: all_data});
console.log(this.state);
})
}
render(){
const { statistics } = this.state;
return !statistics.length ?
<div> Some text </div> :
(
<Homepage statistics={statistics} />
);
}
}
export default App;
Upvotes: 0
Views: 731
Reputation: 811
I believe the issue has nothing to do with the child component.
ComponentDidUpdate
lifecycle method does run after render, but as the state is being updated it triggers the render to run again with the new state.
The problem is your condition.
As the API returns an object and not an array it doesn't have the length property so your condition always is true and render the <div> Nawa oh </div>
element.
You should instead check if the state is an empty object or if the state has keys
return statistics === {} ?
<div> Nawa oh </div> :
(
<Homepage statistics={statistics} />
);
// Or a better way to check if statistics has keys
return Object.keys(statistics).length ? (
<Homepage statistics={statistics} />
) : <div> Nawa oh </div>;
Upvotes: 1
Reputation: 3264
statistics
is an object, it doesn't have a length
property. To check if you have something in statistics
you can use Object.keys
on that object:
return !Object.keys(statistics).length ?
Object.keys(statistics)
returns an array of the object keys, so if your object is empty, it will return an empty array
By the way, in your componentDidMount
, when you do:
this.setState({statistics: all_data});
console.log(this.state);
setState is asynchronous, so console.log won't work
Upvotes: 0