Executing a timeout error with Fetch - React Native

I have a login function that works. But I want to include a time error for extraction. Is there a way to set the timer for 5 seconds or so, which will stop trying to get after such a time? Otherwise, I just get a red screen after a while, reporting a network error.

  _userLogin() { 
    var value = this.refs.form.getValue();
    if (value) { // if validation fails, value will be null
    if (!this.validateEmail(value.email)) {
      Alert.alert(
          "Enter a valid email",
        )
  } else {
      fetch("http://51.64.34.134:5000/api/login", {       
        method: "POST", 
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        timeout: 5000, 
        body: JSON.stringify({
          username: value.email, 
          password: value.password, 
        })
      })
      .then((response) => response.json())
      .then((responseData) => {
        if (responseData.status == "success") {
        this._onValueChange(STORAGE_KEY, responseData.data.token)
        Alert.alert(
          "Login Success!",
        )
        this.props.navigator.push({ name: 'StartScreen'})
        } else if (responseData.status == "error") {
        Alert.alert(
          "Login Error",
          responseData.message
        )
        }
      })
      .done();
    }
  }},    
+8
source share
6 answers

- . , Promises. , . , .

// Rough implementation. Untested.
function timeout(ms, promise) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      reject(new Error("timeout"))
    }, ms)
    promise.then(resolve, reject)
  })
}

timeout(1000, fetch('/hello')).then(function(response) {
  // process response
}).catch(function(error) {
  // might be a timeout error
})

- fetch.js, , , .

+3

, , : ( "" , , )

-, , , -

   const doFetch = (url, callback, data) => { 

    //... creating config obj here (not relevant for this answer)

  var wasServerTimeout = false;

  var timeout = setTimeout(() => {
    wasServerTimeout = true;
    alert('Time Out')
  } , 3000)


      fetch(HOST + url, config)
      .then((response) => { 

        timeout && clearTimeout(timeout); //If everything is ok, clear the timeout

    if(!wasServerTimeout){
        return response.json()
    } 
      })
      .then((response) => {  
              callback && callback( response.data || response ); 
         }).catch((err) => {

           timeout && clearTimeout(timeout); //If something goes wrong, clear the timeout

     if(!wasServerTimeout){
          //Error logic here
       }

         });
    }
+2

ES6, ES , :

export async function fetchWithTimeout(url, options, timeout = 5000) {
    return Promise.race([
        fetch(url, options),
        new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout))
    ]);
}

:

const requestInfo = {
    method,
    headers,
    body,
};
const url = 'http://yoururl.edu.br'
let data = await fetchWithTimeout(url, requestInfo, 3000);
+2

, 2 promises, . , json . , , !

, , . result.status "" json result.data. result.data -. , , !

var yourFetchWrapperFunction = function(method, url, headers, body, timeout=5000){    
var timeoutPromise = new Promise(function(resolve,reject){
                        setTimeout(resolve, timeout, {status: 'error', code: 666, data: 'Verbinding met de cloud kon niet tot stand gebracht worden: Timeout.'});
                      });
    return Promise.race([timeoutPromise, fetch(connectionType + '://' + url, {method: method, headers: headers, body: body})]).then((result) => {
                        var Status = result.status;
                        return result.json().then(function(data){
                          if (Status === 200 || Status === 0) {
                            return {status: 'success', code: Status, data: data};
                          }
                          else {
                            return {status: 'error', code: Status, data: 'Error (' + data.status_code + '): ' + data.message};
                          }
                        },function (response) {
                          return {status: 'error', code: Status, data: 'json promise failed' + response};
                        }).catch((error) => {
                          return {status: 'error', code: 666, data: 'no json response'};
                        });
                      }, function(error){
                          return {status: 'error', code: 666, data: 'connection timed out'};
                      }).catch((error) => {
                          return {status: 'error', code: 666, data: 'connection timed out'};
                      });
}
+1
source

all the paths are right here. but I want to simplify the work, so I am making a retrieval package that uses a timeout race, as well as adding support for retries and bad headers and adding it to npm

try it

0
source

  I can be late, but I made code that works 100% to abort the API request using fetch.

fetch_timeout(url, options) {
    let timeout = 1000;
    let timeout_err = {
      ok: false,
      status: 408
    };
    return new Promise(function (resolve, reject) {
      fetch(url, options).then(resolve, reject).catch(() => {
      alert('timeout.')
      });
      setTimeout(reject.bind(null, timeout_err), timeout);
    });
  }

You just need to pass api-endpointin the URL and bodyin the parameter options.

0
source

Source: https://habr.com/ru/post/1669315/


All Articles