Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Step 3
<script src="../../node_modules/redux-thunk/dist/redux-thunk.min.js"></script>
<script>
(() => {
const callAPIMiddleware = ({dispatch, getState}) => {
return next => action => {
const {
types,
callAPI,
shouldCallAPI = () => true,
payload = {},
} = action;
if (!types) {
// Normal action: pass it on
return next(action);
}
if (!Array.isArray(types) || types.length !== 3 || !types.every(type => typeof type === 'string')) {
throw new Error('Expected an array of three string types.');
}
if (typeof callAPI !== 'function') {
throw new Error('Expected callAPI to be a function.');
}
if (!shouldCallAPI(getState())) {
return;
}
const [requestType, successType, failureType] = types;
dispatch(
Object.assign({}, payload, {
type: requestType,
})
);
return callAPI()
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
})
.then(
response => {
return response.json().then(json => {
return dispatch(
Object.assign({}, payload, {
json,
type: successType,
})
);
});
},
error =>
dispatch(
Object.assign({}, payload, {
error,
type: failureType,
})
)
);
};
};
App.Middleware = [
ReduxThunk.default,
callAPIMiddleware,
];
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment