Last active
February 5, 2024 10:44
-
-
Save endymion1818/33f290c6719fed7f8eec7d6db7d1ac14 to your computer and use it in GitHub Desktop.
fetch
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
async function getStuff(token) { | |
const body = {} | |
// wrap in try / catch so we can resolve any network failures | |
try { | |
// initial request | |
const result = await fetch(`https://example.com/api/v1`, { | |
headers: { | |
"x-CSRF-Token": token, | |
"Content-Type": "application/json" | |
}, | |
body: JSON.stringify(body) | |
}) | |
// API will return any errors in the first call | |
if(!result.ok) { | |
console.error(`The API is not OK`); | |
return false | |
} | |
const data = await result.json() | |
// Don't just assume the data is going to be there | |
if(!data ?? data.error) { | |
console.error(`The API returned an error: ${data.error.message}`); | |
return false; | |
} | |
// OK no erros so we assume the payload is what we needed | |
return data | |
// handle any network errors | |
} catch (error) { | |
console.error('there was a network error') | |
return false // or whatever | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment