Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native fetch not calling then or catch

I am using fetch to make some API calls in react-native, sometimes randomly the fetch does not fire requests to server and my then or except blocks are not called. This happens randomly, I think there might be a race condition or something similar. After failing requests once like this, the requests to same API never get fired till I reload the app. Any ideas how to trace reason behind this. The code I used is below.

const host = liveBaseHost;
const url = `${host}${route}?observer_id=${user._id}`;
let options = Object.assign({
        method: verb
    }, params
    ? {
        body: JSON.stringify(params)
    }
    : null);
options.headers = NimbusApi.headers(user)
return fetch(url, options).then(resp => {
    let json = resp.json();
    if (resp.ok) {
        return json
    }
    return json.then(err => {
        throw err
    });
}).then(json => json);
like image 280
Baran Kucukguzel Avatar asked Jan 04 '17 15:01

Baran Kucukguzel


3 Answers

Fetch might be throwing an error and you have not added the catch block. Try this:

return fetch(url, options)
  .then((resp) => {
    if (resp.ok) {
      return resp.json()
        .then((responseData) => {
          return responseData;
        });
    }
    return resp.json()
      .then((error) => {
        return Promise.reject(error);
      });
  })
  .catch(err => {/* catch the error here */});

Remember that Promises usually have this format:

promise(params)
  .then(resp => { /* This callback is called is promise is resolved */ },
        cause => {/* This callback is called if primise is rejected */})
  .catch(error => { /* This callback is called if an unmanaged error is thrown */ });

I'm using it in this way because I faced the same problem before.

Let me know if it helps to you.

like image 166
Facundo La Rocca Avatar answered Nov 10 '22 02:11

Facundo La Rocca


Wrap your fetch in a try-catch:

let res;
try {
    res = fetch();
} catch(err) {
    console.error('err.message:', err.message);
}

If you are seeing "network failure error" it is either CORS or the really funny one, but it got me in the past, check that you are not in Airplane Mode.

like image 2
Noitidart Avatar answered Nov 10 '22 01:11

Noitidart


I got stuck into this too, api call is neither going into then nor into catch. Make sure your phone and development code is connected to same Internet network, That worked out for me.

like image 1
Prabhjyot Singh Avatar answered Nov 10 '22 00:11

Prabhjyot Singh