How to fetch data from Microsoft Custom Vision API using ReactJS - 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 });
}

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!

Why am I getting empty array in fetch request to MongoDB from ReactJS?

I am trying to fetch all the articles from a document in MongoDB in React. It is perfectly working in Backend with NodeJS when I tested with Postman. But in Frontend , React, I am getting empty array. How to solve this.
Server.js (Backend)
app.get('/api/articles', async (req, res)=>{
const client = await MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser:true, useUnifiedTopology:true})
const db = client.db('my-blog')
const articleInfo= await db.collection('articles').find({}).toArray(function(err, result){
if (err) console.log(err)
res.status(200).send(result)
client.close()
})
})
articlePage.js (FrontEnd)
componentDidMount(){
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
};
const fetchdata = fetch('/api/articles/').then(res=>res.json())
.then(data=>this.setState({articles:data}))
console.log(this.state.articles)
}
Api address is set up in package.json with proxy:http://localhost:8000
How to get the documents data from MongoDB in React?
Firstly, check if you the API call went through to the server from your React app. If it has, then check for the response code in the network. In your case, 200 is where you get the desired result from the API. If you are not getting the desired result, then check your collection and document names and also arguments your are passing in the query.
As setState is not synchronized, you have to access it in the callback.
this.setState({ articles: data }, () => {
console.log(this.state.articles)
})

React Native Formik handleSubmit does not read return values from function

Good day!
Im having a weird experience using formik today,
I am currently working on an app that uses formik to handle forms and will do an API request inside the onSubmit() function of formik.
Every thing went well except when i use API request and wait for it's callback.
Somehow the things inside the function of onSubmit will work properly but the API callback value does not return unless i perform a UI Change in the app itself (like pressing random spots on my screen to trigger ui change).
Here is a look of my onSubmit function of formik
onSubmit={values => {
console.log("before")
let response = FunctionWithApiRequest(values);
console.log("after")
response.then((res) => {
console.log(res)
})
}}
and here is my function with api request inside
const FunctionWithApiRequest = (credentials) => {
return fetch(`${AppConfig.HOSTNAME}/v2/auth/signup`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials)
})
.then((response) => response.json())
.then((responseJson) => {
return responseJson
})
.catch((error) => {
console.log(error)
});
}
The return "responseJson" will only appear inside the onsubmit function when i perform a UI Change (like clicking random spots in my react native screen)
i was wondering what is the problem and what cause the bug.
Thank you for your response in advance.
Possibly you can do this in a separate function with await and async.For instance
async handleSubmit(){
let {credentials} = this.state
let data = await this.props.FunctionWithApiRequest(credentials)
this.setState({returnedData: data})
}
And now in your textInput/formik
onSubmit={()=>this.handleSubmit()}
I assume you have made the request api function in actions.file, not in the same file.Am i right?So what i have done is just put await before call.Which means next line will execute only when you have response returned.Comment down if you have any issue.
It was caused by the haul bundler, when you enable dugging mode.

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!
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.

Proper way to use fetch with github api v3?

I want to map all the issue titles for a repo and render them to li in a react component. I've been able to extract only the issue title using octokat library but unfortunately that library does not play nice with some other stuff i've got going on. Also, I'm sure i can do this with es6 and the fetch api.
Original Post:
Been having a hellava time finding info on using es6 fetch / promises with the github api. I'm trying to fetch issues for a repo but i'm obviously missing something... I've used a few different libraries to try and accomplish this but I'd like to just use fetch.
Update: Now my new goal is merely to console.log the titles... baby steps.
import React from "react";
export default class extends React.Component {
constructor() {
super()
this.state = {
issues: []
}
}
componentWillMount() {
// let issueArry = []
const url = "https://api.github.com/repos/fightplights/chode-stream/issues"
fetch(url)
.then(response => response) // i've tried with and without .json()
.then(body => console.log(body))
// this logs the same response
}
render() {
return (
<div>
<ul>
{here i will map this.state.issues (once i can get them =))}
</ul>
</div>
)
}
}
I know it's a simple error on my part. I'm still a fledgling. =)
...and obviously i need to render to the dom (not shown here)
#Andy_D is right that I wasn't parsing the body of the response, only the response itself (doh!) however now that i'm trying to data.map(issue => ...) I still get the error that data.map() is not a function. This leads me to believe that the data object is not the object the droids are looking for... hand waves in front of screen
Here's the response object in the first promise:
Response {
type: "cors",
url: "https://api.github.com/repos/fightp…",
redirected: false,
status: 200,
ok: true,
statusText: "OK",
headers: Headers,
bodyUsed: false
}
But when I take that response in the next
.then(data => console.log(data))
It is undefined...
I have tried returning the first response => response.json() (as andy suggested) but it's already json... am i wrong?
You need to read the JSON from the body of the response, what you are attempting to render is the full response body.
So:
fetch(url)
.then(response => response.json())
.then(data => data.map(...)
response.json() returns a promise, so you can .then it, the return value (data) will be the JS object/array you're looking for.
https://developer.mozilla.org/en-US/docs/Web/API/Body/json

Resources