Skip to content

Instantly share code, notes, and snippets.

@mozmorris
Created September 15, 2016 15:57
Show Gist options
  • Save mozmorris/4d9d446a49fcd64fd5c3246743f924b6 to your computer and use it in GitHub Desktop.
Save mozmorris/4d9d446a49fcd64fd5c3246743f924b6 to your computer and use it in GitHub Desktop.
Example of generating request (fetch, success, failure) flux actions
const REQUEST = 'REQUEST';
const SUCCESS = 'SUCCESS';
const FAILURE = 'FAILURE';
/**
* Returns request constants (request, success, failure) for a given action
* @param {String} action The request action (e.g. GET_CUSTOMER)
* @return {object} Object containing the contstants
*/
function constantsCreator(action) {
return [REQUEST, SUCCESS, FAILURE].reduce(
(result, type) => Object.assign({}, result, { [type]: `${action}_${type}` }),
{}
);
}
/**
* Returns an action
* @param {String} type The action type
* @param {Object} [payload={}] The action payload
* @return {Object} The action
*/
function actionCreator(type, payload = {}) {
return { type, ...payload };
}
// Create action constants for getCustomer
const GET_CUSTOMER = constantsCreator('GET_CUSTOMER');
// Object of GET_CUSTOMER actions
const customer = {
request: id => actionCreator(GET_CUSTOMER.REQUEST, { id }),
success: (id, response) => actionCreator(GET_CUSTOMER.SUCCESS, { id, response }),
failure: (id, error) => actionCreator(GET_CUSTOMER.FAILURE, { id, error }),
};
export {
GET_CUSTOMER, // Constants
customer, // Actions
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment