Skip to content

Instantly share code, notes, and snippets.

@jacobp100
Last active August 22, 2016 09:45
Show Gist options
  • Save jacobp100/027aa6c2a88eb61bc3665569ef4aaadb to your computer and use it in GitHub Desktop.
Save jacobp100/027aa6c2a88eb61bc3665569ef4aaadb to your computer and use it in GitHub Desktop.
const FETCH = '@@middleware/fetch/FETCH';
export default (baseUrl, fetchImplementation) => () => next => async action => {
if (action.type === FETCH) {
const { method, path, body } = action;
const params = { method };
if (body) params.body = JSON.stringify(body);
const url = baseUrl + path;
const response = await fetchImplementation(url, params);
if (!response.ok) throw new Error('Failed to fetch');
const responseBody = await response.json();
return responseBody;
} else {
next(action);
}
}
export const fetchJson(method, path, body) => ({
type: FETCH,
method,
path,
body,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment