Last active
July 18, 2016 10:43
-
-
Save chodorowicz/75d2bb29f347595f74bf96bc7dac1608 to your computer and use it in GitHub Desktop.
redux middlewares
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
/** | |
* bare middleare | |
*/ | |
export default function({ dispatch }) { | |
return next => action => { | |
console.log(action); | |
// send this action to next middleware or reducers if that's the last middleware | |
next(action); | |
} | |
} | |
/** | |
* simple promise middleware | |
* https://www.udemy.com/react-redux-tutorial/learn/v4/t/lecture/4709458 | |
*/ | |
export default function({ dispatch }) { | |
return next => action => { | |
// If action does not have payload | |
// or, the payload does not have a .then property | |
// we dont care about it, send it on | |
if (!action.payload || !action.payload.then) { | |
return next(action); | |
} | |
// Make sure the action's promise resolves | |
action.payload | |
.then(function(response) { | |
// create a new action with the old type, but | |
// replace the promise with the reponse data | |
const newAction = { ...action, payload: response }; | |
dispatch(newAction); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment