Skip to content

Instantly share code, notes, and snippets.

@selfcontained
Last active May 16, 2016 22:25
Show Gist options
  • Save selfcontained/9e15dbcbd24bfff8c20f6e2173e00834 to your computer and use it in GitHub Desktop.
Save selfcontained/9e15dbcbd24bfff8c20f6e2173e00834 to your computer and use it in GitHub Desktop.
define sync & async redux actions
// Useful for defining a standard synchronous action
exports.defineAction = function (actions, definition) {
var {name, type} = definition
var [actionFn, notification] = parseActionProps(definition)
// pass in `type` via `this` context object
var actionWrapper = function () {
var context = {
type: type
}
return actionFn.apply(context, arguments)
}
actionWrapper.type = type
actionWrapper.notification = notification
actions[name] = actionWrapper
// return action fn
return actionWrapper
}
// Useful for defining a standard async action that has a corresponding success/failure action
exports.defineAsyncActions = function (actions, definition) {
var {name, type} = definition
// normalize success/failure action definitions, add `name` & `type`
var success = exports.defineAction(actions, {
...(typeof definition.success === 'function' ? { action: definition.success } : definition.success),
name: name + 'Success',
type: type + '.' + 'SUCCESS'
})
var failure = exports.defineAction(actions, {
...(typeof definition.failure === 'function' ? { action: definition.failure } : definition.failure),
name: name + 'Failure',
type: type + '.' + 'FAILURE'
})
// main action
var [actionFn, notification] = parseActionProps(definition.action)
actions[name] = function () {
var originalArgs = arguments
return function (dispatch, getState) {
var context = {
type,
success,
failure,
dispatch,
getState
}
return actionFn.apply(context, originalArgs)
}
}
actions[name].type = definition.type
actions[name].notification = notification
// retrurn main async action
return actions[name]
}
function parseActionProps (action) {
var actionFn = typeof action === 'function' ? action : action.action
var notification = action.notification
if (!actionFn || typeof actionFn !== 'function') {
throw new Error('Invalid action definition for ' + action.name)
}
// TODO: consider returning an object as new props are added
return [actionFn, notification]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment