Skip to content

Instantly share code, notes, and snippets.

@ezekielchentnik
Created July 16, 2019 13:40
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 ezekielchentnik/e3ada0f7bb5ba55a9890c33c8d3654fd to your computer and use it in GitHub Desktop.
Save ezekielchentnik/e3ada0f7bb5ba55a9890c33c8d3654fd to your computer and use it in GitHub Desktop.
naive global state in react
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