I'm making a currency convert app that is using an API. When I fetch to the API the data
variable has the JSON that I need. But when I store it to a the global variable, and console.log
that, the output is null
.
CODE:
const API_URL = 'SECRET';
let currency_json = null;
//Makes the request
async function getJSONdata(url) {
loading.style.display = '';
fetch(url)
.then(res => res.json())
.then(data => {
console.log(data); //Outputs the JSON. For some reason it gives null
currency_json = data;
})
.catch(err => console.log(err))
loading.style.display = 'none';
}
//Calls the function
getJSONdata(API_URL);
console.log(currency_json); //Outputs null
Also it doesn't give any errors. And I have read another person's solution on another website (To add Timeout somewhere), problem is they didn't said where or how to put it.
You're making an async
call. Fetch gets data, but it is not available right away.
You need to wait for data to be available. Inside then
you wait for it to be available and that's why it's working.
You could use async/async, but it seems you're making the call at a module level and that's not available there. You should move your code to execute from inside the promise callback (then method).
What you've heard about setTimeout
is a form of long polling
, you could implement it something like this
const longPollCallback = () => {
if (currency_json) {
console.log(currency_json)
} else {
setTimeout(longPollCallback, 500)
}
}
setTimeout(longPollCallback, 500)
But you should rely on then
, async/await
instead of long polling.