Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native fetch return status code + json

I use fetch in react-native to make API calls.

I need to get status code (200 , 401, 404 ) and the response data.

This work to get the response data :

return fetch(url)
.then(response => {
  return response.json();
})
.then(res => {
  console.log("reponse :", res); // <-------- res is ok with data
 })    .catch(error => {
  console.error(error);
  return { name: "network error", description: "" };
});

Now i tweak the first then to get the status code but data is not what i except

return fetch(url)
.then(response => {
  const statusCode = response.status;
  const data = response.json();
  return { statusCode, data };
})
.then(res => {
  console.log("reponse :", res); // <-------- i get a "promise"
 }).catch(error => {
  console.error(error);
  return { name: "network error", description: "" };
});

the console log :

  {statusCode: 200, data: Promise}
like image 261
AlainIb Avatar asked Sep 20 '17 07:09

AlainIb


People also ask

How fetch data from JSON in React Native?

In React Native, you can request data from an API over the network using the fetch() method. We are creating a function called getUsers, where we will fetch json data from rest api. We want to fetch the data as soon as the component mounts, so calling getUsers function in useEffect hook.

How do you know if fetch was successful?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.


1 Answers

response.json() returns a promise, you should wait until it will be fulfilled. To do that you can use Promise.all with array of two elements: statusCode and response.json() call:

return fetch(url)
  .then(response => {
    const statusCode = response.status;
    const data = response.json();
    return Promise.all([statusCode, data]);
  })
  .then([res, data] => {
    console.log(res, data);
  })
  .catch(error => {
    console.error(error);
    return { name: "network error", description: "" };
  });

//EDIT you can create a function who process the response

function processResponse(response) {
  const statusCode = response.status;
  const data = response.json();
  return Promise.all([statusCode, data]).then(res => ({
    statusCode: res[0],
    data: res[1]
  }));
}

and use it the then()

 return fetch(url)
    .then(processResponse)
    .then(res => {
        const { statusCode, data } = res;
        console.log("statusCode",statusCode);
        console.log("data",data);
    }) .catch(error => {
    console.error(error);
    return { name: "network error", description: "" };
  });
like image 196
alexmac Avatar answered Oct 10 '22 15:10

alexmac