Skip to content

Instantly share code, notes, and snippets.

@whatupdave
Last active August 29, 2015 14:21
Show Gist options
  • Save whatupdave/8adebb76ed4069a28fd0 to your computer and use it in GitHub Desktop.
Save whatupdave/8adebb76ed4069a28fd0 to your computer and use it in GitHub Desktop.
connectToStores
import React from 'react'
export default function connectToStores(...stores) {
return function(Component) {
return class StoreConnection extends React.Component {
constructor(props) {
super(props)
this.state = Component.getPropsFromStores()
this.handleStoresChanged = this.handleStoresChanged.bind(this)
}
render() {
return <Component {...this.props} {...this.state} />;
}
componentDidMount() {
stores.forEach(store =>
store.addChangeListener(this.handleStoresChanged)
);
}
componentWillUnmount() {
stores.forEach(store =>
store.removeChangeListener(this.handleStoresChanged)
);
}
handleStoresChanged() {
this.setState(Component.getPropsFromStores())
}
}
}
}
@connectToStores(ChangelogStore, SessionStore)
export default class ApplicationNavbar extends React.Component {
static getPropsFromStores() {
return {
user: SessionStore.user,
changelog: ChangelogStore.changelog
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment