Last active
June 30, 2016 22:47
-
-
Save viniciusdacal/3852493497e23afbd3b711371cac34d6 to your computer and use it in GitHub Desktop.
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
export function callAPIMiddleware(store) { | |
const { dispatch, getState } = store; | |
return next => action => { | |
const { | |
types, | |
callAPI, | |
payload = {}, | |
} = action; | |
const state = getState(); | |
if (!types) { | |
// Normal action: pass it on | |
return next(action); | |
} | |
const [requestType, successType, failureType] = types; | |
dispatch({ ...payload, type: requestType}); | |
return callAPI().then(onSuccess, onError); | |
function onSuccess(res) { | |
dispatch({ | |
...payload, | |
type: successType, | |
body: res.body, | |
lastFetched: Date.now() | |
}); | |
} | |
function onError(err) { | |
dispatch({ | |
...payload, | |
type: failureType, | |
body: err.body | |
}); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment