How to get response body and response headers in one block

Viewed 8871

I'm new to react-native I'm sending a request to server and want to get response and body at same block so that I can send both items to an other function my fetch method is looks like

send_request = (data) =>{
  url = BASE_URL + "some/url.json"
  fetch(url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      user: {
        email: data.email,
        full_name: data.name,
      }
    })
  }).then((response) => {
    //how can I get response body here so that I can call following method
    // this.use_response(responsebody, response.headers)
    return response.json()
  }).then((responseJson) => {
    // or how can I get response headers here so that I can call following fuction
    // this.use_response(responseJson, headers)
    return responseJson
  }).catch((error) => {
    console.log(error)
  });
}

How can I use both at once please help thanks in advance!

2 Answers

response.headers is an object that is available as is, while request.json() is a promise that needs to be resolved.

In order to get them in one place, with plain ES6 promises, there should be either nested thens:

  ...
  .then((response) => {
    return response.json().then(responseJson => {
      this.use_response(responseJson, response.headers)
    });
  })

Or multiple values should be passed through chain altogether as an array or object:

  ...
  .then((response) => {
    return Promise.all([response.json(), response.headers]);
  }).then(([responseJson, headers]) => {
    this.use_response(responseJson, headers)
  })

Or since React application isn't restricted to ES5/ES6 and can use all features that Babel supports, async..await can be used instead which can solve this kind of problems naturally:

send_request = async (data) =>{
  url = BASE_URL + "some/url.json"
  const response = await fetch(url, {...})
  const responseJson = await response.json();
  this.use_response(responseJson, response.headers);
}

Easiest way I see is to send the header to the send_request function and when you have your response, wrap them into one object and return them.

Related