Skip to content

Instantly share code, notes, and snippets.

@georg3103
Created May 15, 2020 15:01
Show Gist options
  • Save georg3103/cf6e7e2ca58f7a1a1f461f702c11342c to your computer and use it in GitHub Desktop.
Save georg3103/cf6e7e2ca58f7a1a1f461f702c11342c to your computer and use it in GitHub Desktop.
const Context = React.createContext()
function connect (mapStateToProps) {
return (Component) => {
class Receiver extends React.Component {
componentDidMount() {
const { subscribe } = this.props.store
this.unsubcribe = subscribe(() => this.forceUpdate())
}
componentWillUnmount() {
this.unsubcribe()
}
render() {
const { dispatch, getState } = this.props.store
const state = getState()
const stateNeeded = mapStateToProps(state)
return <Component {...stateNeeded} dispatch={dispatch} />
}
}
class ConnectedComponent extends React.Component {
render() {
return (
<Context.Consumer>
{(store) => <Receiver store={store}/>}
</Context.Consumer>
)
}
}
return ConnectedComponent
}
}
class Provider extends React.Component {
render() {
return (
<Context.Provider value={this.props.store}>
{this.props.children}
</Context.Provider>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment