Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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