Kartiikeya
Kartiikeya

Reputation: 2516

GetHTTPSttaus Code Fetch API-- React Native

Hitting Login API will return either success or failure response. Response codes will be. between 200 and 300 for success. Rest will be categorised as failure response. In my Scenario if its success response it will be text(response.text()). For failure cases it will yield Json(response.json()).

I want to serialise response based on failure and success.

Approach I have followed upto now

fetch(restUrl, {
method: "POST",
headers: {

    'Accept': '*/*',
    'Content-Type': 'application/json',
},
body: JSON.stringify(objReq)
}))

.then(response => {

            if (response.status >= 200 && response.status < 300) {
                response.text()
            } else {
                response.json()

            }

        )
        .then(responseJson => {

            let obj = responseJson;
            if (responseJson != null && responseJson != undefined) {} else {

                alert(i18n.t('unable'));
            }
        })
        .catch(error => {


            alert(error + "-from error");

        });

Its not accepting this kind of approach. Please provide a suitable solution.

Upvotes: 0

Views: 366

Answers (1)

Atul
Atul

Reputation: 2300

I think you are looking for something like this

const fetchRequest = (restUrl, objReq) => fetch(restUrl, {
    method: "POST",
    headers: {
      'Accept': '*/*',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(objReq)
  })
  .then(response => {
    if (response.status >= 200 && response.status < 300) {
      return response.text()
    } else {
      throw response.json();
    }
  })
  .then(responseText => {
    console.log('success',responseText);
  })
  .catch(errorJson => {
    console.log(errorJson);
  });

And u can call it like this.

fetchRequest('url.com',{test:123});

In essence, just throw the response when u get status code other than 200 and also u forgot to return the promise

Upvotes: 2

Related Questions