Created
October 5, 2016 18:35
-
-
Save markmur/5ec19808cc120fe85c0eba800eca9220 to your computer and use it in GitHub Desktop.
Redux Promise 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
/** | |
* 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