Skip to content

Instantly share code, notes, and snippets.

@kellyrmilligan
Last active May 10, 2017 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellyrmilligan/d8ded8c71ca30a2d26e5db66b8f85673 to your computer and use it in GitHub Desktop.
Save kellyrmilligan/d8ded8c71ca30a2d26e5db66b8f85673 to your computer and use it in GitHub Desktop.
reduce boilerplate in handling fetch responses and errors in redux actions
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