How to dispatch multiple async actions in one function in Redux?
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!