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!
React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.
In React Native, you can request data from an API over the network using the fetch() method. The syntax is simple as follows: fetch('https://examples.com/data.json'); We simply pass the URL to the fetch method to make a request.
Using the React Query library Here, we used axios in the fetching function but we can also use the fetch() method. The object returned by useQuery is destructured, thus we have the information we need in our render.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With