Skip to content

Instantly share code, notes, and snippets.

@almost
Last active August 29, 2015 14:26
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 almost/07d674c6851f9c05f531 to your computer and use it in GitHub Desktop.
Save almost/07d674c6851f9c05f531 to your computer and use it in GitHub Desktop.
A simple mixin for getting state from Flux stores in a React view. An example of how simple it can be. You're probably better off using a full library though...
"use strict";
var shallowEqual = require('shallow-equals');
// Create a mixin for a component that depends on a store(s) for
// state. Component should define getStateFromStores
module.exports = function StoreWatchMixin(...stores) {
return {
componentDidMount () {
stores.forEach((store) => {
store.addListener('change', this.onStoreChange);
});
},
componentWillMount () {
this.setState(this.getStateFromStores(this.props));
},
componentWillUnmount () {
stores.forEach((store) => {
store.removeListener('change', this.onStoreChange);
});
},
componentWillReceiveProps (nextProps) {
if (!shallowEqual(nextProps, this.props)) {
this.setState(this.getStateFromStores(nextProps));
}
},
onStoreChange () {
this.setState(this.getStateFromStores(this.props));
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment