Skip to content

Instantly share code, notes, and snippets.

@ifours
Last active January 8, 2020 10:56
Show Gist options
  • Save ifours/45eead5d5212c8d8d91da1427be04a2f to your computer and use it in GitHub Desktop.
Save ifours/45eead5d5212c8d8d91da1427be04a2f to your computer and use it in GitHub Desktop.
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
export default function combine(mapConnectsToProps) {
const connectsKeys = Object.keys(mapConnectsToProps);
const combinedMapStateToProps = (state, ownProps) => {
const stateProps = {};
connectsKeys.forEach((connectKey) => {
const mapStateToProps = mapConnectsToProps[connectKey].mapStateToProps;
if (mapStateToProps) {
stateProps[connectKey] = mapStateToProps(state, ownProps);
}
});
return stateProps;
};
const combinedMapDispatchToProps = (dispatch, ownProps) => {
const dispatchProps = {};
connectsKeys.forEach((connectKey) => {
const mapDispatchToProps = mapConnectsToProps[connectKey].mapDispatchToProps;
if (mapDispatchToProps) {
dispatchProps[connectKey] = typeof mapDispatchToProps === 'object' ?
bindActionCreators(mapDispatchToProps, dispatch) :
mapDispatchToProps(dispatch, ownProps);
}
});
return dispatchProps;
};
const combinedMergeProps = (stateProps, dispatchProps, ownProps) => {
const mergedProps = {};
connectsKeys.forEach((connectKey) => {
const statePropsForKey = stateProps[connectKey];
const dispatchPropsForKey = dispatchProps[connectKey];
mergedProps[connectKey] = { ...statePropsForKey, ...dispatchPropsForKey };
});
return { ...ownProps, ...mergedProps };
};
return function useCombineConnect(Component) {
return connect(
combinedMapStateToProps,
combinedMapDispatchToProps,
combinedMergeProps,
)(Component);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment