Created
November 10, 2016 08:42
-
-
Save insin/526b7b006039c16f8b2987a80372170c to your computer and use it in GitHub Desktop.
Redux duck utils
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
// Matches the naming convention for functions which select from Redux state | |
const SELECTOR_NAME_RE = /^get[A-Z]/ | |
/** | |
* Creates a function which creates same-named action dispatchers from an object | |
* whose function properties are action creators, passing along any arguments. | |
* Function properties whose names start with "get" will be ignored, as these | |
* are assumed to be selectors by convention. | |
* Also makes the dispatch function itself available. | |
* (If this was Java, it'd be a class named ActionDispatcherFactoryFactory). | |
*/ | |
export const createActionDispatchers = (actionCreators) => (dispatch) => | |
Object.keys(actionCreators).reduce((actionDispatchers, name) => { | |
let actionCreator = actionCreators[name] | |
// Only create dispatchers for non-selector functions - this allows "duck" | |
// modules to export action creators, action type constants and selectors | |
// as needed while still allowing use of "import *" to import all action | |
// creators. | |
if (typeof actionCreator == 'function' && !SELECTOR_NAME_RE.test(name)) { | |
// An action dispatcher calls the action creator it wraps, passing any | |
// given arguments, then calls the Redux store's dispatch() function with | |
// the resulting action object. | |
actionDispatchers[name] = (...args) => dispatch(actionCreator(...args)) | |
} | |
return actionDispatchers | |
}, {dispatch}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment