Skip to content

Instantly share code, notes, and snippets.

@icsaba
Last active October 21, 2020 18:01
Show Gist options
  • Save icsaba/86c75399de0b52cc7c541d6b116062c6 to your computer and use it in GitHub Desktop.
Save icsaba/86c75399de0b52cc7c541d6b116062c6 to your computer and use it in GitHub Desktop.
an actionCreator method for redux-thunk that helps you to reduce boilerplate code and creates async actions
/** Usage
*
* file: someAction.js
*
* export const SOMEVAR = 'SOMEVAR';
*
* export function fetchSomething(callbackOnDone, ...args) {
* return actionCreator({
* actionName: SOMEVAR,
* getResult(data) { return data.someProperty },
* serviceCallback: myService.postCall,
* resolveCallback: callbackOnDone,
* }, ...args);
* }
*
* in the reducer:
* ...
* switch(action.type) {
* case Symbol.for(`REQUEST_${SOMEVAR}`):
* return {... };
* case Symbol.for(`FAILED_${SOMEVAR}`):
* return {... };
* case Symbol.for(`SUCCEED_${SOMEVAR}`):
* return {... };
* }
* ...
*/
function getDataFromBackend(meta, ...args) {
return (dispatch) => {
dispatch(request(meta.actionName));
return meta.serviceCallback(...args)
.then(response => response.json())
.then(data => {
if ('error' in data) {
return dispatch(failed(meta.actionName, data.error));
}
if (meta.resolveCallback) {
meta.resolveCallback();
}
return dispatch(succeed(meta.actionName, meta.getResult(data)));
},
(error) => dispatch(failed(meta.actionName, error.toString()))
);
}
}
function request(actionName) {
return { type: Symbol.for(`REQUEST_${actionName}`) };
}
function failed(actionName, errorMsg) {
return { type: Symbol.for(`FAILED_${actionName}`), error: errorMsg };
}
function succeed(actionName, data) {
return { type: Symbol.for(`SUCCEED_${actionName}`), data };
}
/**
* @typedef {Object} Meta
* @property {Function} serviceCallback
* @property {Function} getResult
* @property {string} actionName
* @property {Function} [resolveCallback]
*
*
* @param {Meta} meta
* @param {...any} args
* @return {Function}
*/
export default (meta, ...args) => {
Symbol(`REQUEST_${meta.actionName}`);
Symbol(`FAILED_${meta.actionName}`);
Symbol(`SUCCEED_${meta.actionName}`);
return getDataFromBackend(meta, ...args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment