Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handle network request failed in react native

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

like image 592
Tanveerbyn Avatar asked Oct 01 '18 07:10

Tanveerbyn


1 Answers

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/

like image 192
JRK Avatar answered Oct 05 '22 03:10

JRK