Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save mattmccray/ddca4a6fda436295f34b to your computer and use it in GitHub Desktop.

Select an option

Save mattmccray/ddca4a6fda436295f34b to your computer and use it in GitHub Desktop.
Alt StoreStateMixin
import alt from 'data/alt'
export function StoreStateMixin( ...stores) {
stores= stores.map(( store)=>{
if( typeof( store) === 'string') {
return alt.getStore( store)
}
else {
return store
}
})
return {
getInitialState() {
return (this.getStoreState) ? this.getStoreState() : {}
},
componentWillMount() {
if( this.getStoreState) {
stores.forEach(( store)=>{
store.listen( this._updateStateFromStores)
})
}
},
componentWillUnmount() {
stores.forEach(( store)=>{
store.unlisten( this._updateStateFromStores)
})
},
_updateStateFromStores() {
this.setState( this.getStoreState())
}
}
}
import {StoreStateMixin} from 'mixins' // app-specific, obviously
import {StoreA, StoreB} from 'data' // or wherever
export let MyComponent= React.createClass({
mixins: [
StoreStateMixin( StoreA, StoreB)
],
getStoreState() {
return {
whatever: StoreA.getWhatever(),
storeB: StoreB.getState()
}
},
render() {
let {whatever, storeB}= this.state
return (
<div>
{ whatever}
</div>
)
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment