Last active
October 21, 2020 18:01
-
-
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
This file contains 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
/** 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