Last active
January 8, 2020 10:56
-
-
Save ifours/45eead5d5212c8d8d91da1427be04a2f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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