Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing a Timeout Error with Fetch - React Native

I have a user login function that is working. But, I want to incorporate a time out error for the fetch. Is there a way to set up a timer for 5 seconds or so that would stop trying to fetch after such a time? Otherwise, I just get a red screen after a while saying network error.

_userLogin() {
  var value = this.refs.form.getValue();
  if (value) {
    // if validation fails, value will be null
    if (!this.validateEmail(value.email)) {
      // eslint-disable-next-line no-undef
      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();
    }
  }
}
like image 980
Arsalan S. Avatar asked Feb 09 '17 22:02

Arsalan S.


People also ask

How do you set timeout in fetch react native?

Timeout a fetch() request First, const { timeout = 8000 } = options extracts the timeout param in milliseconds from the options object (defaults to 8 seconds). const controller = new AbortController() creates an instance of the abort controller. This controller lets you stop fetch() requests at will.

How do I set timeout in fetch request?

To set request timeout with Fetch API, we can use the AbortController constructor. const controller = new AbortController(); const timeoutId = setTimeout(() => controller. abort(), 5000); const req = async () => { const response = await fetch(url, { signal: controller.

Does node fetch have a timeout?

In Node. js, no default timeout is set for fetch() requests, but the newly added AbortSignal.


1 Answers

// Wrapper function for fetch
const fetchSomething = async () => {
    let controller = new AbortController()
    setTimeout(() => controller.abort(), 3000);  // abort after 3 seconds
    const resp = await fetch('some url', {signal: controller.signal});
    const json = await resp.json();
    if (!resp.ok) {
        throw new Error(`HTTP error! status: ${resp.status}`);
    }
    return json;
}


// usage
try {
    let jsonResp = await fetchSomthing();
    console.log(jsonResp);
} catch (error) {
    if (error.name === 'AbortError') {
        console.log('Network Error');
    } else {
        console.log(error.message);
    }
}

I think using AbortController is the recommended way to abort a fetch call. The code snippet above handles the following scenarios:

  1. If network is good but HTTP returns an error status, the message "HTTP error! ..." will be logged.
  2. If network is down, setTimeout would trigger the AbortController to abort fetch after three seconds. The message "Network Error" will be logged.
  3. If network is good and HTTP response is good, the response JSON will be logged.

The documentation for using AbortController to abort fetch is here.

like image 176
Fanchen Bao Avatar answered Sep 29 '22 13:09

Fanchen Bao