Last active
July 6, 2017 15:15
-
-
Save kaisermann/11d0bc926f153e84ebe6935ed1b84084 to your computer and use it in GitHub Desktop.
Redux routine creator utility - async action types and action creators
This file contains hidden or 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
/* Generates an action creator FSA compliant | |
* Based on 'redux-actions' createAction method | |
* https://github.com/acdlite/redux-actions/blob/master/src/createAction.js | |
*/ | |
export default function createAction (type, payloadTransform, metaTransform) { | |
return (...args) => { | |
const action = { type } | |
const payload = | |
args[0] instanceof Error || typeof payloadTransform !== 'function' | |
? args[0] | |
: payloadTransform(...args) | |
if (payload instanceof Error) action.error = true | |
if (payload !== undefined) action.payload = payload | |
if (typeof metaTransform === 'function') { | |
action.meta = metaTransform(...args) | |
} | |
return action | |
} | |
} |
This file contains hidden or 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 createAction from './createAction' | |
/* | |
* Utility to create async routine action creators and action types | |
* Creates a ${prefix}_TRIGGER, ${prefix}_REQUEST, ${prefix}_SUCCESS, | |
* ${prefix}_FAILURE, ${prefix}_FULLFILL | |
* | |
* Returns an object containing the action types and creators | |
*/ | |
const suffixes = ['TRIGGER', 'REQUEST', 'SUCCESS', 'FAILURE', 'FULLFILL'] | |
export default function createRoutine ( | |
prefix = '', | |
payloadTransform, | |
metaTransform | |
) { | |
prefix = prefix.toUpperCase() | |
return suffixes.reduce((acc, suffix) => { | |
const type = `${prefix}_${suffix}` | |
// Uppercase properties should denote the action type | |
acc[suffix] = type | |
// Lowercase properties should denote the action creators | |
acc[suffix.toLowerCase()] = createAction( | |
type, | |
payloadTransform, | |
metaTransform | |
) | |
return acc | |
}, {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment