Skip to content

Instantly share code, notes, and snippets.

@JaySunSyn
Created January 19, 2018 18:39
Show Gist options
  • Save JaySunSyn/d4c9f8c9253c8eb978b93fa18304d3b5 to your computer and use it in GitHub Desktop.
Save JaySunSyn/d4c9f8c9253c8eb978b93fa18304d3b5 to your computer and use it in GitHub Desktop.
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