Skip to content

Instantly share code, notes, and snippets.

@markmur
Created October 5, 2016 18:35
Show Gist options
  • Save markmur/5ec19808cc120fe85c0eba800eca9220 to your computer and use it in GitHub Desktop.
Save markmur/5ec19808cc120fe85c0eba800eca9220 to your computer and use it in GitHub Desktop.
Redux Promise Middleware
/**
* Promise Middleware is used to avoid having to dispatch 3 events for every
* request (request, success and error)
*
* You can dispatch 1 event with a `promise` property and in turn the Middleware
* will automatically dispatch the 3 events.
* @method promiseMiddleware
* @return {Promise} returns the promise
*/
export default function promiseMiddleware({ getState }) {
return (next) => (action) => {
const { promise, type, ...props } = action;
// Ignore non async actions
if (!promise) return next(action);
// Dispatch the first request event
next({ type, ...props });
return promise.then(
// dispatch the success event
(response) => {
return next({
type: `${type}_SUCCESS`,
response,
...props
});
},
// dispatch the error event
(error) => {
// User is not logged in, redirect to /login
if (error.status === 403) {
window.location.href = '/login';
return;
}
next({
type: `${type}_ERROR`,
error: {
responseText: error.responseText,
status: error.status,
statusText: error.statusText
},
...props
});
}
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment