Last active
February 12, 2019 01:21
-
-
Save dotjosh/e8fef7664eef672200d0c7af510b1950 to your computer and use it in GitHub Desktop.
Promise Redux Thunk Middleware
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
//Your action before | |
export const query = dispatch => { | |
dispatch("MYTYPE_START"); | |
myAPI.query() | |
.then(resp => dispatch("MYTYPE_SUCCESS", resp)) | |
.catch(err => dispatch("MYTYPE_ERROR", err); | |
} | |
//Your action after | |
export const query = () => ({ | |
type: "MYTYPE", | |
$promise: myAPI.query() | |
}); | |
//Middleware | |
export default store => next => action => { | |
if (typeof action === "function") { | |
return action(store.dispatch, store.getState); | |
} | |
const { $promise, ...rest } = action; // eslint-disable-line no-redeclare | |
if (!$promise) { | |
return next(action); | |
} | |
const START = `${rest.type}_START`, | |
SUCCESS = `${rest.type}_SUCCESS`, | |
FAILURE = `${rest.type}_FAILURE`; | |
next({ ...rest, type: START }); | |
const actionPromise = | |
typeof $promise === "function" | |
? $promise(store.dispatch, store.getState) | |
: $promise; | |
actionPromise | |
.then( | |
result => next({ ...rest, result, type: SUCCESS }), | |
error => next({ ...rest, error, type: FAILURE }) | |
) | |
.catch(error => { | |
console.error("MIDDLEWARE ERROR:", error); | |
next({ ...rest, error, type: FAILURE }); | |
}); | |
return actionPromise; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment