Last active
May 10, 2017 13:53
-
-
Save kellyrmilligan/d8ded8c71ca30a2d26e5db66b8f85673 to your computer and use it in GitHub Desktop.
reduce boilerplate in handling fetch responses and errors in redux actions
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
function isJson (response) { | |
const contentType = response.headers.get('content-type') | |
return contentType && contentType.indexOf('application/json') !== -1 | |
} | |
export function handleResponse (response) { | |
if (response.ok) { | |
if (isJson(response)) { | |
return response.json() | |
} else { | |
return response.text() | |
} | |
} else { | |
const error: ErrorT = new Error(response.statusText) | |
error.response = response | |
throw error | |
} | |
} | |
export function handleError(reject, dispatch, errAction) { | |
return function(err) { | |
if (err.response && isJson(err.response)) { | |
err.response.json() | |
.then((errBody) => { | |
err.body = errBody | |
reject(err) | |
dispatch(errAction(err)) | |
}) | |
} else { | |
reject(err) | |
dispatch(errAction(err)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment