Skip to content

Instantly share code, notes, and snippets.

@viniciusdacal
Last active June 30, 2016 22:47
Show Gist options
  • Save viniciusdacal/3852493497e23afbd3b711371cac34d6 to your computer and use it in GitHub Desktop.
Save viniciusdacal/3852493497e23afbd3b711371cac34d6 to your computer and use it in GitHub Desktop.
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