Skip to content

Instantly share code, notes, and snippets.

@deanohyeah
Created August 18, 2018 20:53
Show Gist options
  • Save deanohyeah/a88bb85edc1dd4ca5047a3f1b6151d2c to your computer and use it in GitHub Desktop.
Save deanohyeah/a88bb85edc1dd4ca5047a3f1b6151d2c to your computer and use it in GitHub Desktop.
Js fetch boilerplate
const makeRequest = async function ({
url,
body = {},
method = 'GET',
headers = {},
}) {
const bodyString = JSON.stringify(body)
let json
const response = await fetch(url, {
method,
body: bodyString,
headers: {
'Content-Type': 'application/json',
...headers,
},
})
if (!response.ok) {
let message = `Failed api request to ${url}`
try {
const responseText = await response.text()
if (responseText) {
message += responseText
}
} catch (e) {
throw new Error(`Api request to ${url}: ${message} ${response.status}`)
}
}
try {
// incase the the server returns invalid json
json = await response.json()
} catch (e) {
return ''
}
return json
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment