Last active
August 28, 2022 04:42
-
-
Save Fredkiss3/8328d7d570bf9d8a96dd0e6540eb0042 to your computer and use it in GitHub Desktop.
JSON FETCH
This file contains hidden or 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 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)); | |
} |
This file contains hidden or 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 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); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MERCI