Api fetch responses Blob structure in React Native app

I'm consuming a web api from my React Native Android project. After updating my react-native version to 0.60.3 my response data is not returning JSON, it returns Blob data structure.

This is what I get from then(res=>{...})

Please look at the image

Screen-Shot-2019-07-18-at-17-25-10.png

The _bodyInit object was returning JSON. But now it returns Blob that I can not reach from Js code.

I tried using functions res.json(), res.text() They worked! But this time I just got data inside the _bodyInit. I can not reach other parameters like ok, header etc.

This is what I've tried. Like I said, it works. But it returns response with just my data, not other parameters like ok, headers etc.

.then((res) => res.json())
.then((res) => {
   if (res.ok) {
    // No 'ok' element anymore after .json()
  }
});

In the 'devtools' if I click the '_bodyInit' object. Simulator gives error below.

Screen-Shot-2019-07-18-at-17-32-49.png

Do you have any idea to solve this issue? Thanks in advance!

2 answers

  • answered 2019-07-19 08:33 Anurag Awasthi

    ok property is with response before you call json method on it. If your response contains json, call json to serialize body as json, if response contains blob, call .blob to serialize body as blob. See more proerties of Response here.

    .then((res) => {
        console.log("response.ok", res.ok)
    
        // print headers,
        console.log("headers", res.headers.forEach(item=>console.log(item)))
    
        // if response if json, call res.json
        return res.json()
    })
    .then((res) => {
       // here you will only get json data, not other properties.
       console.log("json data is ", res)
    });
    

  • answered 2019-07-19 09:10 Enes Öztürk

    SOLVED I found two way to solve this problem.

    1. Using .then() after using .json()
    .then((res) => {
     if (res.ok) {
      res.json().then(res=>{
       console.log(res)
      })
     } else console.log("not ok")
    });
    
    1. Using async and await
    .then(async res => {
     if(res.ok) {
       const response = await res.json()
       console.log(response)
     } else console.log("not ok")
    })
    

    That would be great to see other solutions from you. Thanks.