Created
November 15, 2021 03:26
-
-
Save kishoreandra/3dcc691ff294fee8420a6623364d4afe to your computer and use it in GitHub Desktop.
Reusbale fetch api with error handling
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 fetchData(header, query, url) { | |
try { | |
const timeout = 8000; | |
const controller = new AbortController(); | |
const id = setTimeout(() => controller.abort(), timeout); | |
const response = await fetch(url, { | |
method: "POST", | |
headers: { ...header }, | |
body: JSON.stringify(query), | |
timeout: timeout, | |
signal: controller.signal, | |
}); | |
clearTimeout(id); | |
if (!response.ok) { | |
const message = `An error has occured: ${response.status}`; | |
throw new Error(message); | |
} | |
const data = await response.json(); | |
return data; | |
} catch (error) { | |
return { err: error }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment