Last active
September 9, 2016 08:01
-
-
Save salanki/0af4dfb820aacf086471e8a78de39ce7 to your computer and use it in GitHub Desktop.
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
// lib/actions.js | |
import identity from 'lodash/identity'; | |
export const ActionType = { | |
REQUEST: 'REQUEST', | |
SUCCESS: 'SUCCESS', | |
FAILURE: 'FAILURE' | |
}; | |
function createActionCreatorFlat(prefix, type, requestPayloadCreator = identity) { | |
const baseType = `${prefix}/${type}`; | |
const request = (...args) => ({ | |
type: baseType + '/REQUEST', | |
baseType: baseType, | |
payload: requestPayloadCreator(...args), | |
actionType: ActionType.REQUEST, | |
}); | |
const success = (payload) => ({ | |
type: baseType + '/SUCCESS', | |
baseType: baseType, | |
payload, | |
actionType: ActionType.SUCCESS, | |
}); | |
const failure = (payload) => ({ | |
type: baseType + '/FAILURE', | |
baseType: baseType, | |
payload, | |
error: true, // FSA Compatibility | |
actionType: ActionType.FAILURE, | |
}); | |
const either = (payload) => | |
(payload instanceof Error) ? failure(payload) : success(payload); | |
return { | |
request, | |
success, | |
failure, | |
either | |
}; | |
} | |
export const createActionCreator = | |
(prefix) => | |
(type, requestPayloadCreator = identity) => | |
createActionCreatorFlat(prefix, type, requestPayloadCreator); | |
// Usage | |
// createActionCreator(prefix)(name, requestPayloadCreator = Identity) | |
import { createActionCreator, ActionType } from 'lib/actions' | |
const createAction = createActionCreator('FEED') | |
const FETCH_FEED = createAction('FETCH_FEED', (contentType, ordering) => {contentType, ordering}) | |
const LOAD_FEED = createAction('LOAD_FEED', (contentType, ordering) => {contentType, ordering}) | |
const SAVE_FEEDS = createAction('SAVE_FEEDS') | |
// Request action creator | |
FETCH_FEED.request('polls', 'recent') | |
// Success action creator. Payload is just set directly on action, no mapping is supported in action | |
FETCH_FEED.success('foo') | |
> | |
> { | |
> type: 'FEED/FETCH_FEED/SUCCESS' | |
> baseType: 'FEED/FETCH_FEED', | |
> payload: 'foo', | |
> actionType: ActionType.SUCCESS | |
> } | |
// Error action creator. Should it be called error or failure? Payload is just set directly on action, no mapping is supported in action | |
FETCH_FEED.failure('bar') | |
> | |
> { | |
> type: 'FEED/FETCH_FEED/FAILURE' | |
> baseType: 'FEED/FETCH_FEED', | |
> payload: 'bar', | |
> actionType: ActionType.FAILURE | |
> } | |
FETCH_FEED.SUCCESS | |
> 'FEED/FETCH_FEED/SUCCESS' | |
FETCH_FEED.BASE | |
> 'FEED/FETCH_FEED' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment