Skip to content

Instantly share code, notes, and snippets.

@tuckerconnelly
Created April 6, 2018 17:09
Show Gist options
  • Save tuckerconnelly/bf4e65a0894c5c11da64d4c9257db1cb to your computer and use it in GitHub Desktop.
Save tuckerconnelly/bf4e65a0894c5c11da64d4c9257db1cb to your computer and use it in GitHub Desktop.
import { Component, Children } from 'react'
import PropTypes from 'prop-types'
let _globalState = {}
let _listener = () => 0
export function setGlobalState (name, value) {
_globalState[name] = value
_listener()
}
export class GlobalStateProvider extends Component {
static propTypes = {
children: PropTypes.element.isRequired,
initialGlobalState: PropTypes.object
}
static defaultProps = {
initialGlobalState: {}
}
static childContextTypes = {
globalState: PropTypes.object.isRequired
}
getChildContext () {
return { globalState: this.state.globalState }
}
state = {
globalState: _globalState
}
constructor (props) {
super(props)
_globalState = props.initialGlobalState
}
componentWillMount () {
_listener = () => this.setState({globalState: _globalState})
}
render () {
return Children.only(this.props.children)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment