Last active
July 19, 2020 09:48
-
-
Save szkrd/533ebfcc40db8806a22ea2c12dfe5800 to your computer and use it in GitHub Desktop.
react redux typescript fancy connect (with IDE code completion)
This file contains 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 store, { IState } from '../../actions' | |
import { connect } from 'react-redux' | |
const isFunc = (item) => typeof item === 'function' | |
const isNotFunc = (item) => !isFunc(item) | |
const filter = (obj, comp) => { | |
return Object.keys(obj).reduce((acc, key) => { | |
if (comp(obj[key])) { | |
acc[key] = obj[key] | |
} | |
return acc | |
}, {}) | |
} | |
const getMapStateToProps = (obj) => filter(obj, isNotFunc) | |
const getMapDispatchToProps = (obj) => filter(obj, isFunc) | |
export class Connectable { | |
protected state: IState | |
constructor(state: IState) { | |
this.state = state | |
} | |
} | |
const autoConnect = (StateItemsAndDispatchers, Component) => | |
connect( | |
(state: IState) => getMapStateToProps(new StateItemsAndDispatchers(state)), | |
getMapDispatchToProps(new StateItemsAndDispatchers(store.getState())) | |
)(Component) | |
export default autoConnect | |
// -------------------------------------------- | |
// usage: | |
export class ModifyModalComponentProps extends Connectable { | |
modifyVideoState = this.state.global.modals.modifyVideo // state to prop | |
current = this.state.user.current // state to prop | |
videoModify = videoModifyAction // dispatch to prop | |
videoRequest = videoRequestAction // dispatch to prop | |
} | |
const ModifyModalContainer = autoConnect(ModifyModalComponentProps, ModifyModalComponent) | |
export default ModifyModalContainer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment