How to dispatch multiple async actions in one function in Redux?

Vladimir Strilets | Web Developer
2 min readJun 21, 2020

--

Hi, redux lovers. How it’s going on?

Let’s assume the next situation: you are working on a complex React App and when your client opens the page for the first time, you want to do several async fetching calls with Redux-Thunk to grab your data from some API.

Your mapStateToProps and destructuring props may look like:

// imports
...
const App = ({
fetchDataAsync1,
fetchDataAsync2,
fetchDataAsync3,
fetchDataAsync4,
fetchDataAsync5,
}) => {
useEffect(() => {
fetchDataAsync1(),
fetchDataAsync2(),
fetchDataAsync3(),
fetchDataAsync4(),
fetchDataAsync5(),
},[]);
return (<>My App</>)
};
const mapDispatchToProps = (dispatch) => ({
fetchDataAsync1: () => dispatch(fetchDataAsync1()),
fetchDataAsync2: () => dispatch(fetchDataAsync2()),
fetchDataAsync3: () => dispatch(fetchDataAsync3()),
fetchDataAsync4: () => dispatch(fetchDataAsync4()),
fetchDataAsync5: () => dispatch(fetchDataAsync5()),
})
export default connect(null, mapDispatchToProps)(App);

Oh, I have to write the same functions for 4 times 🤨.

Is there some workaround? Yes.

Let's create an array of all our async functions that need to be called. After that, our dispatch function will be just simple .map. Code example? Sure:

// imports
...
const App = ({
fetchAllData,
}) => {
useEffect(() => {
fetchAllData(),
},[]);
return (<>My App</>)
};
const allActions = [
fetchDataAsync1(),
fetchDataAsync2(),
fetchDataAsync3(),
fetchDataAsync4(),
fetchDataAsync5(),
];
const mapDispatchToProps = (dispatch) => ({
fetchAllData: () => {
allActions.map((action) => dispatch(action));
},
})
export default connect(null, mapDispatchToProps)(App);

I think now it looks more elegant. And it works!

See you next time!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response