Skip to content

Instantly share code, notes, and snippets.

@kishoreandra
Created November 15, 2021 03:26
Show Gist options
  • Save kishoreandra/3dcc691ff294fee8420a6623364d4afe to your computer and use it in GitHub Desktop.
Save kishoreandra/3dcc691ff294fee8420a6623364d4afe to your computer and use it in GitHub Desktop.
Reusbale fetch api with error handling
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