-
-
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
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
// 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