Skip to content

Instantly share code, notes, and snippets.

@djmccormick
Last active February 18, 2016 04:19
Show Gist options
  • Save djmccormick/68c37d1bd35f05d9b2a0 to your computer and use it in GitHub Desktop.
Save djmccormick/68c37d1bd35f05d9b2a0 to your computer and use it in GitHub Desktop.
An ES6 decorator for syncing Alt.js store changes with React components. This is similar to Alt.js's connectToStores higher-order component, except implemented as a decorator to avoid the problems that come with higher-order components. getStores (return an array of stores to listen to) and getStateFromStores (return an object of state updates) …
import React from 'react';
import _ from 'lodash';
export default function (Base) {
return class extends Base {
constructor() {
super();
if (!_.isFunction(this.getStores)) {
throw new Error('connectToStores() expects the decorated component to have a getStores() method.');
}
if (!_.isFunction(this.getStateFromStores)) {
throw new Error('connectToStores() expects the decorated component to have a getStateFromStores() method.');
}
}
componentDidMount() {
if (super.hasOwnProperty('componentDidMount')) {
super.componentDidMount();
}
let stores = this.getStores();
if (_.isArray(stores)) {
this.storeListeners = stores.map(store => store.listen(this.onStoreChanged));
}
this.onStoreChanged();
}
componentWillUnmount() {
if (super.hasOwnProperty('componentWillUnmount')) {
super.componentWillUnmount();
}
if (_.isArray(this.storeListeners)) {
this.storeListeners.forEach(unlisten => unlisten());
}
}
onStoreChanged = () => {
this.setState(this.getStateFromStores());
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment