Skip to content

Instantly share code, notes, and snippets.

@Fredkiss3
Last active August 28, 2022 04:42
Show Gist options
  • Save Fredkiss3/8328d7d570bf9d8a96dd0e6540eb0042 to your computer and use it in GitHub Desktop.
Save Fredkiss3/8328d7d570bf9d8a96dd0e6540eb0042 to your computer and use it in GitHub Desktop.
JSON FETCH
export async function jsonFetch<T>(
url: string,
options: RequestInit = {}
): Promise<T> {
// Set the default headers correctly
const headers: HeadersInit = new Headers(options.headers);
headers.set('Accept', 'application/json');
headers.set('Content-Type', 'application/json');
if (process.env.NODE_ENV === 'development') {
// in dev mode, simulate a loading time
await wait(1500);
}
return fetch(url, {
...options,
headers,
credentials: 'include'
})
.then(async (response) => {
// check if data is JSON
const isJson =
response.headers.get('content-type')?
.includes('application/json') ?? false;
const data = isJson ? await response.json() : null;
if (!response.ok) {
throw new Error(data);
}
return data;
})
.catch((error) => {
console.error(`[jsonFetch ${options.method ?? 'GET'} ${url}] There was an error :`, error);
throw error;
});
}
export function wait(ms: number): Promise<void> {
// Wait for the specified amount of time
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function jsonFetch(url, options) {
// Set the default headers correctly
const headers: HeadersInit = new Headers(options.headers);
headers.set('Accept', 'application/json');
headers.set('Content-Type', 'application/json');
return fetch(url, {
...options,
headers,
credentials: 'include',
})
.then((response) => response.json())
.catch((error) => {
console.error('There was an error ?', error);
});
}
@jojojojojoj5564656465465

MERCI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment