Skip to content

Instantly share code, notes, and snippets.

@mhart
Created April 7, 2017 16:05
Show Gist options
  • Select an option

  • Save mhart/6ca15a54541caae04a075db76b68c06c to your computer and use it in GitHub Desktop.

Select an option

Save mhart/6ca15a54541caae04a075db76b68c06c to your computer and use it in GitHub Desktop.
One way to manage React global state with EventEmitters
const EventEmitter = require('events')
class ActivityStore extends EventEmitter {
constructor() {
this.state = 'stopped' // Whether you need this or not...?
}
start() {
this.state = 'started'
this.emit('started', this.state)
}
stop() {
this.state = 'stopped'
this.emit('stopped', this.state)
}
}
exports.activityStore = new ActivityStore()
{activityStore} = require('./activityStore')
class ActivityComponent1 extends React.Component {
constructor(props) {
super(props)
this.state = {activity: 'stopped'}
activityStore
.on('started', activity => this.setState({activity}))
.on('stopped', activity => this.setState({activity}))
}
render() {
return <h1>Activity has: {this.state.activity}</h1>
}
}
class ActivityComponent2 extends React.Component {
constructor(props) {
super(props)
this.state = {activity: 'stopped'}
activityStore
.on('started', activity => this.setState({activity}))
.on('stopped', activity => this.setState({activity}))
}
render() {
return <h1>Activity has: {this.state.activity}</h1>
}
}
module.exports = {ActivityComponent1, ActivityComponent2}
// Replace the store with a test stub (maybe the real one talks to an API or something)
require('./activityStore').activityStore = require('./activityStoreStub')
// Now your components will require your test stub
{ActivityComponent1, ActivityComponent2} = require('./components')
// Test away!
// For more complicated stubbing, see https://github.com/thlorenz/proxyquireify
@mhart
Copy link
Author

mhart commented Apr 7, 2017

Keeping in good opinion-throwing fashion, this code is totally untested.

Hopefully you get the... wait for it... gist

@rjattrill
Copy link

Well it might be untested but it works and it is the only sample I have found on the web that actually does. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment