Wednesday, September 14, 2022

Improved fetch for REST API communication

Problem Statement: fetch or Axios does not throw error in case of domain is not valid or API does not respond in timely manner (like 5 -8 seconds which is acceptable) fetch or Axios relies on timeout defined within Browsers which is too high (1 minute for Brave, 5 minutes for Chrome)

Solution: Here is the improvised fetch function which can be used to avoid endless delays. It simply returns an objects after defined timeout so you can show toast message or throw a popup to user. 

Approach is very easy and simple.

const fetcher = async (URL, timeout) => {
    console.log(URL, timeout);
    try {
        const controller = new AbortController();
        const id = setTimeout(() => controller.abort(), timeout);

        const response = await fetch(URL, {
            method: 'GET', // *GET, POST, PUT, DELETE, etc.
            // mode: 'cors', // no-cors, *cors, same-origin
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            // credentials: 'same-origin', // include, *same-origin, omit
            headers: {
                'Content-Type': 'application/json'
                // 'Content-Type': 'application/x-www-form-urlencoded',
            },
            redirect: 'follow', // manual, *follow, error
            referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
            signal: controller.signal
            // body: JSON.stringify(data) // body data type must match "Content-Type" header
        })
        clearTimeout(id);
        return response.json(); // parses JSON response into native JavaScript objects
    } catch(err) {
        return { "error": "connection failure",err }
    }
}

export { fetcher }