Last active
August 29, 2015 14:26
-
-
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...
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
"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