Skip to content

Instantly share code, notes, and snippets.

@rrcobb
Last active May 12, 2017 16:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rrcobb/b774b61bd336fb72a189f783009052e2 to your computer and use it in GitHub Desktop.
Save rrcobb/b774b61bd336fb72a189f783009052e2 to your computer and use it in GitHub Desktop.
Function for turning a Redux reducer into a Reflux store, so that you can migrate code from Reflux to Redux. http://fin.com/eng-blog/from-reflux-to-redux
// Rob Cobb 2016 for Fin
// fin.com/eng-blog/from-reflux-to-redux
//
// function for turning a redux reducer into a reflux store.
var Reflux = require('reflux');
const capitalize = (string) => string.charAt(0).toUpperCase() + string.slice(1);
export default function StoreFromReducer(Reducer, ActionCreators) {
let store = {
name: Reducer.StoreName || 'store',
listenables: Reducer.RefluxActions,
init: function () { this.DATA = Reducer(undefined, {type: "default"}) },
getInitialState: function () { return this.DATA },
getState: function () { return this.DATA },
dispatch: function (action) {
// support redux-thunk style action creators
if(typeof action === 'function'){
action = action(this.dispatch, this.getState);
}
let next = Reducer(this.DATA, action);
if (this.DATA !== next) {
this.DATA = next;
if (!action.dontTrigger) {
this.trigger(this.DATA);
}
}
}
};
// create a "onActionName" method for each actionCreator
Object.values(ActionCreators).forEach((actionCreator) => {
store[`on${capitalize(actionCreator.name)}`] = function() {
const action = actionCreator(...arguments);
this.dispatch(action);
}
});
return Reflux.createStore(store);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment