Skip to content

Instantly share code, notes, and snippets.

@szkrd
Last active July 19, 2020 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szkrd/533ebfcc40db8806a22ea2c12dfe5800 to your computer and use it in GitHub Desktop.
Save szkrd/533ebfcc40db8806a22ea2c12dfe5800 to your computer and use it in GitHub Desktop.
react redux typescript fancy connect (with IDE code completion)
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