6

I'm not able to parse the data from the fetch call

Below is the method

onLoginPress=()=>{
      console.log("username="+this.state.username);
      console.log("password="+this.state.password);
      this.sendLoginRequest(this.state.username,this.state.password)
      .then((response) => {
          console.log("RESPONSEEEEEEEEEEEEEEEE");
          console.log(response.text())
          console.log( Promise.resolve(response));
          response.json();
      })
      .then((responseJson) => {

        console.log(responseJson);
      })
      .catch((error) => {
        console.error(error);
      });


    };

The response i get it is a promise and i'm not able to get the token out of it.

Below is the log for response.text()

{ _45: 0, _81: 1, _65: '"3h8112qe2qobox3675ghmq9dtcbjvddc"', _54: null }

For console.log( Promise.resolve(response)) the output is

{ 
_45: 0,
_81: 1,
_65: { type: 'default',
  status: 200,
  ok: true,
  statusText: undefined,
headers: { map: { connection: [ 'Keep-Alive' ],
'content-length': [ '34' ],
'content-type': [ 'application/json; charset=utf-8' ],
'set-cookie': [ 'persistent_shopping_cart=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/' ],
'cache-control': [ 'no-store, no-cache, must-revalidate' ],
expires: [ 'Thu, 19 Nov 1981 08:52:00 GMT' ],
pragma: [ 'no-cache' ],
server: [ 'Apache/2.4.23 (Ubuntu)' ],
'keep-alive': [ 'timeout=5, max=100' ],
[ 'Tue, 20 Jun 2017 06:58:16 GMT' ] } },
 url:'http://integration/customer/token',
 _bodyInit: '"3h8112qe2qobox3675ghmq9dtcbjvddc"',
 _bodyText: '"3h8112qe2qobox3675ghmq9dtcbjvddc"',
 bodyUsed: true 
},
_54: null }

responseJson returns undefined.

How to get the token(3h8112qe2qobox3675ghmq9dtcbjvddc) out of the data.

Thanks!

1 Answer 1

13

It appears that your API is returning text. So you need to call the text() method and return it to chain with a then:

onLoginPress=()=>{
      this.sendLoginRequest(this.state.username,this.state.password)
      .then((response) => {
         return response.text();
      })
      .then((responseJson) => {
         console.log(responseJson);
      })
      .catch((error) => {
         console.error(error);
      });
    };

If your API returns JSON, you would do exactly the same by swapping the text() call by a json() call. See the React Native fetch doc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.