Last active
April 3, 2020 09:45
-
-
Save oriSomething/36492428024fb284bcdd to your computer and use it in GitHub Desktop.
Reflux + React + ES7 decorators
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
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> | |
); | |
} | |
} |
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
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() { | |
// ... | |
} | |
}); |
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
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