Skip to content

Instantly share code, notes, and snippets.

@oriSomething
Last active April 3, 2020 09:45
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oriSomething/36492428024fb284bcdd to your computer and use it in GitHub Desktop.
Save oriSomething/36492428024fb284bcdd to your computer and use it in GitHub Desktop.
Reflux + React + ES7 decorators
import React, { Component } from 'react';
import storeDecorator from './store-decorator';
import someStore, { SOME_STORE_SYMBOL } from './some-reflux-store';
@storeDecorator(someStore)
class SomeComponent extends Component {
render() {
return (
<div>
{this.state[SOME_STORE_SYMBOL].someProperty}
</div>
);
}
}
import Reflux from 'reflux';
import action from './some-action'
export const SOME_STORE_SYMBOL = Symbol();
export default Reflux.createStore({
init() {
this.listenTo(action, 'onAction');
},
getInitialState() {
return {
[SOME_STORE_SYMBOL]: {
someProperty: 'some property'
}
};
}
onAction() {
// ...
}
});
import _ from 'lodash';
const unsubscribes = new Map();
export default function storeDecorator(...stores) {
return function decorator(Component) {
return class StoreComponent extends Component {
constructor(props) {
super(props);
const storesState = _.chain(stores)
.pluck('getInitialState')
.filter(_.isFunction)
.map(f => f())
.value();
this.state = this.state || {};
assign(this.state, ...storesState);
}
componentDidMount() {
if (super.componentDidMount) {
super.componentDidMount();
}
const storesUnsubscribes = _.map(stores, (store) => store.listen(this.setState.bind(this)));
const componentUnsubscribes = (
unsubscribes.has(this) ? unsubscribes.get(this).concat(storesUnsubscribes) : storesUnsubscribes
);
unsubscribes.set(this, componentUnsubscribes);
}
componentWillUnmount() {
if (super.componentWillUnmount) {
super.componentWillUnmount();
}
_.forEach(unsubscribes.get(this), f => f());
}
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment