Reputation: 85
Currently I have a React Redux
application in which I have a whole load of state items in the store. I have actions set up to populate the state from my back end API. I use container and presentational components and in my container I am getting all the state I require for its children using mapDispatchToProps
, and then passing the state down as props using mapStateToProps
.
Currently this is how I'm making those initial API calls in my container component:
componentDidMount() {
this.props.getResources()
.then(() => {
this.props.getUsers()
.then(() => {
this.props.getComments()
.then(() => {
this.props.getFiles()
.then(() => {
this.props.getAlts()
.then(() => {
this.props.getSubjects()
.then(() => {
this.props.getTemplates()
.then(() => {
this.props.getResourceTags()
.then(() => {
this.setState({
resourcesLoaded: true
});
});
});
});
});
});
});
});
});
}
Which just seems ridiculous. Is there a cleaner way to make these API requests or refactor my actions so that they are condensed in to a single action?
Upvotes: 2
Views: 805
Reputation: 2111
The most efficient way it to run all functions/promises concurrently using Promise.all
componentDidMount() {
Promise.all([
this.props.getResources(),
this.props.getComments(),
this.props.getFiles(),
this.props.getAlts(),
this.props.getSubjects(),
this.props.getTemplates(),
this.props.getResourceTags()
]).then(() =>
this.setState({ resourcesLoaded: true })
)
}
The benefit of using Promise.all
over await
is that await
runs every function/promise serially while Promise.all
runs all functions concurrently.
Detailed Explanation
So when we use
await getResources()
await getComments()
...
...
the await
keyword will wait for getResources()
to finish and then it will run getComments()
and wait for its completion and this will go on.
While using Promise.all
, it will run all the functions at once and will wait until every function is executed and only then will run the .then(...)
part.
Upvotes: 5
Reputation: 4068
You can use async - await
instead of callback pattern. This is an ES6 feature.
Example:
async componentDidMount() {
try {
await this.props.getResources()
await this.props.getComments()
await this.props.getFiles()
await this.props.getAlts()
await this.props.getSubjects()
await this.props.getTemplates()
await this.props.getResourceTags()
this.setState({
resourcesLoaded: true
})
} catch (e) {
// in case any function above causes error
}
}
Upvotes: 3