Api fetch responses Blob structure in React Native app - reactjs

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!

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)
});

SOLVED
I found two way to solve this problem.
Using .then() after using .json()
.then((res) => {
if (res.ok) {
res.json().then(res=>{
console.log(res)
})
} else console.log("not ok")
});
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.

Related

Using data received from Axios Post request response

Can someone pls give me some advice?
I need to create a report of all messages I sent via rest API.
I got my rest api post request working. What i need now is to extract some data from the Response and use it outside the Axios request. Ideally in another component. Context API doesn't work.
Data can be grouped into object i called stats.
Thats my axios request:
axios.post(url, glbody, {headers:headers})
.then((response) => {
const stats ={
id: response.data.messages[0].dateTime,
date: response.data.messages[0].dateTime,
from: response.data.messages[0].origin,
to: response.data.messages[0].destination,
status: response.data.messages[0].status,
}
})
.catch((error) => {
console.log(error);
})
}
Thanks!

How to fetch data from Microsoft Custom Vision API using ReactJS

I need some help regarding the use of Custom Vision. I built an image classifier in order to detect car damages.
So what I am trying to do: when I try to input an image and click the submit button, I want to be able to call the Custom Vision API and get the results in order to be able to analyze them later using ReactJS
I tried using AXIOS and the componentDidMount() method, but I can't seem to get a hold of them.
componentDidMount(){
axios.get('url: "https://southcentralus.api.cognitive.microsoft.com/customvision/v3.0/Prediction/...",
// Request headers {
prediction: ("Prediction-Key","xxx");
content: ("Content-Type","xxx");
},
type: "POST",
// Request body
data: imgContent,
processData: false')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
your request type is post and you are using axios.get()
Check your code, // Request headers {
prediction: ("Prediction-Key","xxx");
content: ("Content-Type","xxx");
},
The first bracket seems to be commented out so this may be a potential problem.
You should use async/await with the componentDidMount method.
An example
async componentDidMount() {
const response = await fetch(`https://api.coinmarketcap.com/v1/ticker/?limit=10`);
const json = await response.json();
this.setState({ data: json });
}

How to fetch data from an API correctly with xml2js

I am trying to use the JS fetch() coupled with the npm package xml2js to pull xml data from an API with react and display it with my frontend. I am able to do this with regular data but when it comes down to applying xml2js it is throwing back errors in relation to 'data' not being defined and such. The following code is what I have achieved so far:
fetch(URL)
.then(res => res.text())
.then(data => {
this.setState({
trains: ArrayOfObjStationData.objStationData
});
});
// convert xml to object
var parseString = require('xml2js').parseString;
parseString(data, (err, res) => {
console.log(res.ArrayOfObjStationData.objStationData);
this.setState({data: res.ArrayOfObjStationData.objStationData})
});
I think I am just incorrect about my formatting of the code but any help would be greatly appreciated.

How to handle api error in react and show custom log

componentDidMount() {
let url = FormatUrl(`/user/`)
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data)
}).catch(err => {
if (err){
console.log('has error')
}
})
}
Here i am trying to fetch data from a wrong api.
And it is throwing below error.
Home.jsx:20 GET http://127.0.0.1:8000/user/ net::ERR_CONNECTION_REFUSED
I
Is there any way to hide this error and display a simple message in console without throwing
exceptions.
The promise isn't rejected by the fetch API simply because it fails to reach the endpoint. What you need to do is check the response in your first .then(). You have response.status which returns the status code, or you could use response.ok which returns true if the status code is within the 200-299 interval.
A more detailed explanation can be found here

Axios get data from API - React.js

I am using axios to get data from an API, I am trying to do something very simple and I have done it before.
I can see on the console that my request was made but I cant output the data or a console.log() message.
componentDidMount() {
axios.get("https://dog-api.kinduff.com/api/facts")
.then( response => {
console.log("Facts: ")
this.setState({DogFact:response.data})
})
.catch( err => {
this.setState({error:err.data.message})
})
}
The response from the api is an object with an array.
{facts["fact written here"]}
It should be very simple but If I try that:
axios.get("https://dog-api.kinduff.com/api/facts")
.then( response => {
console.log("Facts: ", response) //This wont show up on the console
this.setState({DogFact:response.facts[0]}) //This wont work.
})
I dont really understand what might be wrong.
Could someone maybe help me out?
add this line in package.json
"proxy": "https://dog-api.kinduff.com/api/"
then in your axios call change it to this:
axios.get("/facts")
.then( response => {
console.log("Facts: ", response)
this.setState({DogFact:response.facts[0]})
});

Resources