Description

Often times the fetch will have a temporary failure that was due to a one off issue in these cases we can retry the fetch.
?

Reach for when

An error outside of your control was reported. Network, internal service error...

Code

async function fetchWithRetry(url, retries = 3, delay = 1000) {
	try {
		const res = await fetch(url);
		if (!res.ok) throw new Error(`HTTP ${res.status}`);
		return await res.json();
	} catch (err) {
		if (i === retries) throw err;
		await new Promise(resolve => {
			setTimeout(async()=>{
				const res = await fetchWithRetry(url, retries-1, delay)
				resolve(res)
			}, delay)
		});
	}
}