Currently in react I have to functions in the componentDidMount lifecycle method in which call action creators to which fetch data. The component uses the data however, dependin
Control your async actions using then
or await
and use this.state
to control whether or not your content gets loaded. Only render your content after this.state.loaded === true
constructor(props) {
super(props)
this.state = {
loaded: false
}
}
async componentDidMount() {
await this.props.getTotalHours()
await this.props.getTrained()
this.setState({loaded: true})
}
content() {
let hours = parseInt(_.map(this.props.hours, 'hours'));
let trained = _.map(this.props.trained, 'trained');
return (
)
}
render() {
return (
{this.state.loaded ? this.content() : null}
)
}
edit: If you care about performance in your API calls, you can run them in parallel with Promise.all
.
async componentDidMount() {
const hours = this.props.getTotalHours()
const trained = this.props.getTrained()
await Promise.all([hours, trained])
this.setState({loaded: true})
}