Last active
November 13, 2021 12:54
-
-
Save justinnoel/57514eba131d8a12f86bb2e399757d5a to your computer and use it in GitHub Desktop.
Helper function to get JSON data from an API call and handle failures.
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
export async function getJson(url, options) { | |
try { | |
const response = await fetch(url, options); | |
const contentType = response.headers.get("content-type"); | |
if (! response.ok || ! contentType.includes("application/json")) { | |
console.log(`ERROR: getJSON -> Invalid Response -> response.status = ${ | |
response.status | |
}`,); | |
console.log(`ERROR: getJSON -> Invalid Response ->response.statusText = ${ | |
response.statusText | |
}`,); | |
console.log(`ERROR: getJSON -> Invalid Response ->response.contentType = ${contentType}`,); | |
return {json: null, error: "request failed"}; | |
} | |
const data = await response.json(); | |
return {data, error: null}; | |
} catch (e) { | |
console.log(`ERROR: getJSON -> exception -> ${ | |
e.message | |
}`); | |
return {data: null, error: "request failed"}; | |
} |
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
const {data, error} = getJson("http://abc123.com"); | |
if (error) { | |
...return; | |
} | |
console.log(data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment