I don’t understand in which order React renders and executes functions… Where should I put promise to fetch data and setState in order to work? I tried in componentDidMount but it gives me an error because I guess when App component is rendered the state is still empty. Should I use different lifecycle method?
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
componentDidMount() {
axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/recent')
.then((res) => {
this.setState({ data: res.data });
});
}
render() {
return (
<div className="App">
<div className="wrapper">
<div className="header">
<p>FreeCodeCamp Leaderboard</p>
</div>
<Headings/>
<User data={this.state.data}/>
</div>
</div>
);
}
};
class User extends Component {
render() {
return (
<div className="user">
<div className="number">1</div>
<div className="camper-name">{this.props.data[0].username}</div>
<div className="thirty-days-points">{this.props.data[0].recent}</div>
<div className="all-time-points">{this.props.data[0].alltime}</div>
</div>
);
}
}