0

Im using fetch API to hit rest server. In case of server is down, I need to set timeout for 30 secs and show alert like 'Timeout happened'.

my Fetch call

 fetch('url', {
            method: "POST",
            headers: {

                'Accept': '*/*',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(objReq)
        })
            .then(response => response.text())
            .then(responseJson => {
                if (responseJson != null && responseJson != undefined) {
            })
            .catch(error => {
                alert(error + " from error")
                console.error(error);
            });

I'm unable to set timeout correctly. Is there a simplified way to implement timeout.Any suggestions on checking internet connectivity before hitting API call.

Kartiikeya
  • 2,358
  • 7
  • 33
  • 68
  • I think you are looking for this - https://facebook.github.io/react-native/docs/netinfo.html#isconnected , will return the connection status – nish Jan 02 '18 at 07:08
  • Check this out https://stackoverflow.com/questions/46946380/fetch-api-request-timeout – Ahsan Ali Jan 02 '18 at 07:14

1 Answers1

1

The referenced answer is the way to go but maybe cleaning to use partial application (closure):

const withTimeout = time => promise =>
  Promise.race(
    [
      promise,
      new Promise(
        (resolve,reject)=>
          setTimeout(
            _=>reject("Timeout happened")
            ,time
          )
      )
    ]
  );
const in30Seconds = withTimeout(30000);

in30Seconds(
  fetch('url', {
    method: "POST",
    headers: {
        // 'x-nanobnk-auth': this.token,
        'Accept': '*/*',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(objReq)
  })
)
  .then(response => response.text())
  .then(responseJson => {
      if (responseJson != null && responseJson != undefined) {

      }
  })
  .catch(error => {
      alert(error + " from error")
      console.error(error);
  });
HMR
  • 37,593
  • 24
  • 91
  • 160
  • Does this close Fetch connectivity too? – Kartiikeya Jan 03 '18 at 06:48
  • @KartiikeyaBaleneni No it does not, but if you can show me how to [cancel a fetch request](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) I can add it for you. When it times out it will not resolve when the fetch is finally finished because a promise can only resolve or reject once. – HMR Jan 03 '18 at 12:55