One possible use of bindActionCreators() is to "map" multiple actions together as a single prop.
A normal dispatch looks like this:
Map a couple common user actions to props.
const mapStateToProps = (state: IAppState) => {
return {
// map state here
}
}
const mapDispatchToProps = (dispatch: Dispatch) => {
return {
userLogin: () => {
dispatch(login());
},
userEditEmail: () => {
dispatch(editEmail());
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
In larger projects mapping each dispatch separately can feel unwieldy. If we have a bunch of actions that are related to each other we can combine these actions. For example a user action file that did all kinds of different user related actions. Instead of calling each action as a separate dispatch we can use bindActionCreators() instead of dispatch.
Multiple Dispatches using bindActionCreators()
Import all your related actions. They are likely all in the same file in the redux store
import * as allUserActions from "./store/actions/user";
And now instead of using dispatch use bindActionCreators()
const mapDispatchToProps = (dispatch: Dispatch) => {
return {
...bindActionCreators(allUserActions, dispatch);
},
};
};
export default connect(mapStateToProps, mapDispatchToProps,
(stateProps, dispatchProps, ownProps) => {
return {
...stateProps,
userAction: dispatchProps
ownProps,
}
})(MyComponent);
Now I can use the prop userAction to call all the actions in your component.
IE:
userAction.login()
userAction.editEmail()
or
this.props.userAction.login() this.props.userAction.editEmail().
NOTE: You do not have to map the bindActionCreators() to a single prop. (The additional => {return {}} that maps to userAction). You can also use bindActionCreators() to map all the actions of a single file as separate props. But I find doing that can be confusing. I prefer having each action or "action group" be given an explicit name. I also like to name the ownProps to be more descriptive about what these "child props" are or where they are coming from. When using Redux + React it can get a bit confusing where all the props are being supplied so the more descriptive the better.