11

I'm facing an issue while using react native fetch api. many times request got failure . I have a high speed connection. but many times it got failed. that issue is happening In android,ios both.

const shoppingApi  = 'myserverlink';

async function Sendshoppinapi(data) {
    try {
        let response = await fetch(shoppingApi, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'content-type':'multipart/form-data'
            },
            body: data
        });
        let responseJson = await response.json();
        return responseJson;
    }
    catch (error) {
          Alert.alert(error.toString())
    }
}

export {Sendshoppinapi};

data that I sending server as post request

  add_to_wishlist = (item,index) => {
        {
          let data = new FormData();
        data.append('methodName',       'add_to_wishlist');
        data.append('user_id',        global.userid)
        data.append('item_id',        this.props.navigation.state.params.itemid.toString())


        Sendshoppinapi(data).then((responseJson)=>{

          console.warn(responseJson);
          if(responseJson.responseCode == '200'){
            this.setState({fav:false})
            Alert.alert('SHOPPING','Item added to wishlist successfully.',[{text: 'OK',},],{ cancelable: false })

          }
          else{
            this.setState({fav:false})
            Alert.alert('SHOPPING','Item already .',[{text: 'OK',},],{ cancelable: false })
          }
        })}
      }

Error that when request got failed error

fullscreen

Tanveerbyn
  • 764
  • 1
  • 10
  • 25

3 Answers3

2

Use then() function with promises. (Requested code snippet)

fetch(shoppingApi, {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'content-type':'multipart/form-data'
    },
    body: data
})
.then((resp) => {
    return resp.json()
})
.then((resp) => {
  //resp contains your json data
});

You also can make your function returns a Promise, and use it with then():

function sendShoppingApi(data) {
    return new Promise((resolve, reject) => {
        fetch(shoppingApi, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'content-type':'multipart/form-data'
            },
            body: data
        })
        .then((resp) => {
            return resp.json();
        })
        .then((resp) => {
            resolve(resp);
            
            /*
              you should also check if data is valid, if something went wrong
              you can reject the promise:
              
              if(!dataOK)
                  reject("error message");
            
            */
        });
    });
}

So now you can do something like this:

sendShoppingApi(data)
.then((resp) => {
    //do stuff with your data
})
.catch((err) => {
    //handle error
});

UPDATE

could be a duplicate of this: React Native fetch() Network Request Failed

Andriy Klitsuk
  • 564
  • 3
  • 14
  • He is using `then()`. But not this way. He is handling Promises using the `async-await` syntax which is just syntactic sugar for `then().catch()` – Andrei Olar Oct 01 '18 at 08:33
  • Maybe `then().catch()` is syntactic sugar for `async-await`. He requested code snippet in OP comments, I provided. The question is badly placed and too generic to provide an answer, BTW using `then().catch()` will bring better code and therefore more ease in debug – Andriy Klitsuk Oct 01 '18 at 08:41
  • again getting the same error like onUnhadled @ promise.js 43:19 and many other – Tanveerbyn Oct 01 '18 at 09:33
2

I've quoted an answer I used for another post - however I have added await.

You can check the status of the call, to determine perhaps why the network call failed. Try using fetch's ok to check whether the response was valid, for example:

.then(function(response) {
    if (!response.ok) {
        //throw error
    } else {
       //valid response
    }
})

Using await:

 let response = await fetch(url)
 if (response.ok) return await response.json()

You can also access the response's status like:

response.status;

or also, statusText such as:

response.statusText;

checkout the below:

https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText

https://developer.mozilla.org/en-US/docs/Web/API/Response/status

https://www.tjvantoll.com/2015/09/13/fetch-and-errors/

JRK
  • 3,686
  • 1
  • 13
  • 19
  • This doesn't explain how to prevent the crash, in cases where the network request fails for reasons that are outside of the client/server's control. – Andrew Koster Oct 17 '19 at 22:40
  • "Network request fails outside the client server control"? Surely you're talking about an application crash? – JRK Nov 03 '19 at 14:54
  • 1
    No, why would you think that I mean that? I mean that the network request fails for a reason that is outside of the client/server code's control. Networks are never 100% reliable, and a network request can fail for any number of reasons that are not a bug in the client or server code. Do I really need to list examples? Surely you've had a router reset because of a power failure in your house, or because of something your ISP did? Surely you've experienced intermittent network availability on a mobile network? – Andrew Koster Nov 04 '19 at 00:02
0

For the case when you are running the app on the android device, the API is on a computer and both of them are on the same network I have added some possible things to check. I haven't detailed specific solutions since there are many answers on each topic.

  • Do a quick check with ngrok https://ngrok.com/ on the free plan to see if that works. If yes:
    • Make sure the API is accessible by trying to access it on the device browser (most important is to check if you allow the port at inbound rules, firewall).
    • If you are using HTTPS, you might get an error if your react native env is not properly configured to accept not trusted certificates, assuming you are using a non trusted one. Do a check without HTTPS, only with HTTP, to see if it's the case. https://github.com/facebook/react-native/issues/20488
Gabriel P.
  • 3,400
  • 2
  • 32
  • 23