Kartiikeya
Kartiikeya

Reputation: 2516

Timeout fetch -React Native

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.

Upvotes: 0

Views: 1724

Answers (1)

HMR
HMR

Reputation: 39280

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);
  });

Upvotes: 1

Related Questions