Reputation: 75
I'm making an API request in JS that is working, but it keeps giving two responses when I'm only expecting one. Here's the code:
CallCoinGecko();
function CallCoinGecko() {
var cgrequest = new XMLHttpRequest();
var url1 = 'https://api.coingecko.com/api/v3/simple/price?ids=';
var id = 'ethereum';
var url2 = '&vs_currencies=USD&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true';
cgrequest.open("GET", url1 + id + url2, true);
cgrequest.send();
cgrequest.onreadystatechange = function () {
if (cgrequest.status == 200) {
var cgresponse = cgrequest.responseText;
var cgobj = JSON.parse(cgresponse);
console.log(cgobj);
var cgprice = (cgobj[id]['usd']);
console.log(cgprice);
}}}
Here is a console image that shows two responses: image
Any thoughts on this are appreciated thanks
Upvotes: 2
Views: 857
Reputation: 1
You should compare the readyState value in your if statement as well.
function CallCoinGecko() {
var cgrequest = new XMLHttpRequest();
var url1 = 'https://api.coingecko.com/api/v3/simple/price?ids=';
var id = 'ethereum';
var url2 = '&vs_currencies=USD&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true';
cgrequest.open("GET", url1 + id + url2, true);
cgrequest.onreadystatechange = function(res){
if (cgrequest.status === 200 && cgrequest.readyState === XMLHttpRequest.DONE) {
var cgresponse = cgrequest.responseText;
var cgobj = JSON.parse(cgresponse);
console.log(cgrequest.status, cgobj);
var cgprice = (cgobj[id]['usd']);
console.log(cgrequest.status, cgprice);
}
};
cgrequest.send();
}
Upvotes: 0
Reputation: 306
Try verifying the value of readyState
after the request. Example:
if (cgrequest.status === 200 && cgrequest.readyState === 4)
The problem is that, as mentioned, the readyState
can have multiple values - therefore everytime it changes, your code to print the response text will trigger. I'm sure if you looked in the network tab, the API request isn't being carried out two times, only your response text is being printed two times. Checking if it is 4
confirms that the request is done - and should only be carried out once.
My hunch that the API isn't being called two times is due to the fact that the data is exactly the same on each console.log()
.
Good luck :)
Upvotes: 2