blog

Attempt re-fecth on network error

When API call fails due to network error this is how to wait 1 second and try again once more before calling it quits.

// Thin wrapper around native fetch that allows
// passing arbitrary number of retries.
const fetchWithRetry = (url, options, retry = 1) => {
return fetch(url, options)
.then((resp) => resp.json())
.catch((error) => {
// fetch throws TypeError for network errors.
// Need to handle other API error is some other way.
if (error instanceof TypeError) {
// In case of NETWORK_ERROR wait for 1s and try re-fetch once.
return new Promise((resolve) => setTimeout(resolve, 1000))
.then(() => fetchWithRetry(url, options, retry - 1))
.catch((error) => {
throw error;
});
}
});
}