Search code examples
reactjsreact-reduxcreate-react-app

create-react-app (react redux) Multiple actions in connect


I am creating a React app with Create-React-App using Redux.

Following a tutorial, all the actions are put into 1 file:

src\action\index.js

export const fetchUser = (useCache = false) => async dispatch => { .. }
export const getUser = (useCache = false) => async dispatch => { .. }
export const fetchAlerts = (useCache = true) => async dispatch => { .. }

and then I connect them to my components using Connect:

import * as actions from "../../actions";

....

export default connect(mapStateToProps, actions)(Home);

However I would like to organize my actions into files, having a Accounts Action, and a Alerts action for this example. And I may want to call functions from each action in the 1 component.

My problem I'm having is I cant figure out how to add multiple actions into the 1 connect statment:

export default connect(mapStateToProps, actions)(Home);

The actions accepts an object or a function... Arrays dont work..


Solution

  • You're almost there, since you know mapDispatchToProp param of connect() can be object as well, you can always use

    Object.assign({}, userAction, alertAction)
    

    Or with object spread operator

    {...userAction, ...alertAction}