Skip to content

Instantly share code, notes, and snippets.

@hkjpotato
Last active July 11, 2017 20:02
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 hkjpotato/46c855875f7a5c28fd81c229219860e0 to your computer and use it in GitHub Desktop.
Save hkjpotato/46c855875f7a5c28fd81c229219860e0 to your computer and use it in GitHub Desktop.
function connectHOC(mapStateToProps, mapDispatchToProps) {
return function wrapWithConnect(WrappedComponent) {
class Connect extends Component {
constructor(props, context) {
super(props, context)
this.store = context.store //access store from context
//get parent's Subscription instance from context
const parentSub = this.context.parentSub
//init its own Subscription instance based on the parent's Subscription
this.subscription = new Subscription(this.store, parentSub, this.onStateChange.bind(this))
}
getChildContext() {
//replace parentSub context for the child component with its own Subscription instance
return {
parentSub : this.subscription
}
}
componentDidMount() {
this.subscription.trySubscribe()
}
onStateChange() {
this.setState({})
}
componentDidUpdate() {
//after the current component get updated, go ahead and notify the nested subscription
this.subscription.notifyNestedSubs()
}
...
}
//the context exposed to container itself
Connect.contextTypes = {
store : storeShape,
parentSub : subscriptionShape,
}
//replace the context of parentSub for the child component
Connect.childContextTypes = {
parentSub: subscriptionShape,
}
return Connect
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment