Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set timeout in Fetch API using react js

Tags:

reactjs

I am using fetch post method in react js and when sending request to backend it takes 7 mints to provide the response and before that front end automatically gets timed out. Can you please help me out how to set 10 mints time in fetch method for front to wait for the response and only gets timed out when backend takes more than 10 mints. Please let us know if i have to install any dependency.

Also just to inform you i have installed dependency "whatwg-fetch-timeout": "^2.0.2-timeout" and it was working fine on development server but when tried to create build package it failed to create build the build. sample code:

fetch("http://" + hostName + ":" + port + "/searchData", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Login: login,
    ID: id
  },
  body: JSON.stringify({
    StartDate: StartDate === "" ? null : StartDate,
    EndDate: EndDate === "" ? null : EndDate,
    FileName: FileName === "" ? null : FileName,
    RecordCount: RecordCount === "" ? null : RecordCount,
    Status: Status
  })
})
  .then(response => {
    resStatus = response.status;
    return response.json();
  })
  .then(responseJson => {
    //source code
  })
  .catch(error => {});
like image 480
Riya Kumari Avatar asked Mar 10 '19 10:03

Riya Kumari


3 Answers

How about add your own timeout Something like

function timeoutPromise(ms, promise) {
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      reject(new Error("promise timeout"))
    }, ms);
    promise.then(
      (res) => {
        clearTimeout(timeoutId);
        resolve(res);
      },
      (err) => {
        clearTimeout(timeoutId);
        reject(err);
      }
    );
  })
}

then call it in ES7 async/await syntax

async request() {
  try { 
    let res = await timeoutPromise(10*60*1000, fetch('/hello'));
  } catch(error) {
    // might be a timeout error
  }
}

Also for ref Fetch API request timeout? try this.

like image 155
Subhendu Kundu Avatar answered Nov 15 '22 04:11

Subhendu Kundu


If you have control over the server, consider sending status code 102 (Still processing) in between the request and the final response, in order to let the client know not to timeout.

like image 36
jorbuedo Avatar answered Nov 15 '22 03:11

jorbuedo


Promise.race can address this.

// "wait" function returns a new Promise that rejects after waiting
const wait = milliseconds => new Promise(
  (res, rej) => setTimeout(
    () => rej(new Error(`timed out after ${milliseconds} ms`)),
    milliseconds
  )
);

// the fetch could remain unchanged
// ...but it helps to add the "signal" property to abort the request early
const abortController = new AbortController();
const fetchData = fetch(
  'http://url',
  {
    method:"POST",
    signal: abortController.signal
  }
);

// now the fetch races against the wait Promise
const fetchOrTimeout = Promise.race([fetchData, wait(10 * 60 * 1000)]);

// ...and the difference here is that now the logic could have a rejected Error from "wait"
// (also this is the place to send the abort signal to fetch)
fetchOrTimeout
.then(response => { console.log('fetch worked!'); return response.json(); })
.catch(error => { console.log(`fetch error: ${error}`); abortController.abort(); });
like image 45
OurNewestMember Avatar answered Nov 15 '22 05:11

OurNewestMember