Created
July 16, 2019 13:40
-
-
Save ezekielchentnik/e3ada0f7bb5ba55a9890c33c8d3654fd to your computer and use it in GitHub Desktop.
naive global state in react
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 React, { Component } from 'react'; | |
class State { | |
constructor() { | |
this.state = {}; | |
this.subscriptions = []; | |
} | |
subscribe(cb) { | |
this.subscriptions.push(cb); | |
return this.subscriptions.lastIndexOf(cb); | |
} | |
unsubscribe(handle) { | |
delete this.subscriptions[handle]; | |
} | |
setState(obj) { | |
this.state = Object.assign({}, this.state, obj); | |
this.subscriptions.forEach(cb => { | |
if(cb) { | |
cb(); | |
} | |
}) | |
} | |
} | |
const _state = new State(); | |
const glue = Component => { | |
return class GluedState extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
state: {} | |
} | |
} | |
componentDidMount() { | |
this.handle = _state.subscribe(this.handleChange.bind(this)); | |
} | |
componentWillUnmount() { | |
_state.unsubscribe(this.handle); | |
} | |
handleChange() { | |
this.setState({ state: _state.state }); | |
} | |
render() { | |
return <Component {...this.props} state={this.state.state} setState={_state.setState.bind(_state)} /> | |
} | |
} | |
} | |
export {glue}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment