Skip to content

Instantly share code, notes, and snippets.

@dotjosh
Last active February 12, 2019 01:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotjosh/e8fef7664eef672200d0c7af510b1950 to your computer and use it in GitHub Desktop.
Save dotjosh/e8fef7664eef672200d0c7af510b1950 to your computer and use it in GitHub Desktop.
Promise Redux Thunk Middleware
//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