Javascript JSON function parsing issue [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 2 years ago.
Having a strange issue where im trying to parse some JSON for use with Chart.JS .. I can console log within the function and use the array so to say as expected but outside of that function even though i have made it a Global variable the array is empty after the function runs and i print it out to the console.
var data = {}
const api_url = "http://localhost:5000/"
var currentPage = window.location.href
currentPage = currentPage.split("/")
currentPage = api_url + currentPage[4]
console.log(currentPage)
async function getJson() {
const response = await fetch(currentPage);
data = await response.json();
console.log(data)
}
getJson()
console.log(data)

Well, you are executing an async function but you don't await.
So, instead of this:
getJson()
Use this:
getJson().then(_ => console.log(data))

Related

Trying to access array fetched from an API in global scope [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 25 days ago.
This post was edited and submitted for review 25 days ago.
I'm doing an API fetch and am trying to use the returned array of objects "stops" elsewhere in the global scope, however I cannot extract this array from the API fetch's scope after the .then() to use in the GLOBAL SCOPE because I am trying to use the array in other local scopes without calling the function in there.
i.e I would like to be able to use the array contained in variable stops in a separately scoped API call.
const fetchBusStopInfo = async () => {
try {
const url = new URL("https://data.edmonton.ca/resource/4vt2-8zrq.json")
url.search = new URLSearchParams ({
"$$app_token": "25u3nAznyYiBSLWIyQ4bmKnde",
"$limit": 100000
});
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.log(error)
return error;
}
}
fetchBusStopInfo().then((stopsArray)=> {
const stops = stopsArray
console.log(stops)
})
Is there a way to get around this so I can use the array found in const stops elsewhere?

How to extract data from fetch? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have a function loadData which attemps to fetch an array of customers. I wonder what is the best way to extract the data "outside"? Right now the only solution I can think of is using an external array and injecting it with data. I do not know however if this is the best practice as the test array is getting mutated in the process. What could an alternative solution be?
const test = [];
const loadData = (async () => {
const customersFetched = await fetch(customers);
const data = await customersFetched.json();
test.push(data);
})();
async function loadData() {
const customersFetched = await fetch(customers);
return await customersFetched.json();
}
const data=loadData();
loadData will return the response array.

How to assign data fetched from Firestore.collection() .get() .then() method to a global variable [duplicate]

This question already has answers here:
How to make the data from Firestore in to a global variable?
(2 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How to get data from firestore DB in outside of onSnapshot
(1 answer)
Closed 1 year ago.
I want to fetch data (a particular field in a doc) from Firebase FireStore → Assign that value to global variable → console.log that value.
My Research till now:
I tried assigning the value to global variable → NOT WORKING
I tried returning the fetched value
var a = firestore.collection("collection1").doc("doc1").get().then(){ return doc.data().FIELD}
removing the return keyword from the above
Currently I am doing nested code like console.log() inside the then().
What my code looks like now
var a = "BEFORE";
console.log(a); // BEFORE
firestore.collection("collection1").doc("doc1").then(
function(doc) {
const myData = doc.data();
a = myData.Reciept_Series;
console.log(a); // DESIRED_VALUE
}
)
console.log(a); //BEFORE
How can I make a = DESIRED_VALUE ie. How can I use the value that I got from FireStore .
Thanks in advance.
In the following code, the handler is called as soon as the Firebase returns your data
function handler(a) {
// here you can work with a
}
firestore.collection("collection1").doc("doc1")
.then(doc => doc.data)
.then(myData => myData.Reciept_Series)
.then(handler)
.catch(console.error); // to debug: make sure the error (if any) is always reported
If you want to wait for the data, use async/await pattern:
(async function() {
var a = await firestore.collection("collection1").doc("doc1")
.then(doc => doc.data)
.then(myData => myData.Reciept_Series)
// here you can work with a
})();
Keep in mind that the Promise (returned by then()) is run asynchronously, so your code is not executed in top-down order, but as another task.
You can call await on top level just in modules, otherwise the main thread would be blocked by it. See the support table at the bottom of the linked page.
Your global variable is assigned, but asynchronously. Give the code some time and then click the following button:
<button onclick="console.log(a)">Log data</button>

Can I store the result of Fetch in a global variable using JavaScript? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 2 years ago.
I have a JSON file that I store in my project and when i Fetch this file I want to store the result in a global variable so I can use it later whenever I want!
So my question is: is it there a way to put this data into a global variable something like this:
let globalData;
fetch('./../JSON.json')
.then((response) => response.json())
.then(JsonData => {
globalData = JsonData;
}).catch(error => console.error)
console.log( globalData ) // return undifined
Thank you!
Yes, you can, but at the time that you set the variable, you will have already called console.log. At the time of calling the console.log the variable is not yet set because first, it takes time to perform fetching; second, fetch will not block and allow for the following lines to execute without waiting for it.
If you console log from inside of the callback or create a function outside of fetch and call it, it will print as you expect it to.
Perhaps like this?
let globalData
async function myFunction () {
const res = await fetch('./../JSON.json')
const data = await res.json()
globalData = data
console.log(globalData)
}
myFunction()
Yes, you can, but it'll also be asyncronous. Smth like that:
let globalData = fetch('./../JSON.json')
.then((response) => response.json())
.catch(error => console.error)
log:
console.log( await globalData );
or
globalData.then(result => console.log(result));
It returns undefined on catch.

Is it possible to save the response data from a Fetch to a variable to use later? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 3 years ago.
Using the Fetch API I'm making a GET request to an API endpoint which returns an object. I would like to save this object to use later, outside of the Fetch, but it seems that when I do, the variable I've initialized returns undefined.
I have initialized a variable before the fetch which I set equal to the response data inside a .then call:
const getObject = (convoId) => {
let url = base_url + `/${convoId}`
let convo; //<-- initializing the variable
fetch(url, { method: "GET", headers })
.then(response => response.json())
.then(data => convo = data)
.then(() => console.log(convo)) //<-- successfully logs the data
.catch(err => {
console.error(err);
});
console.log(convo); //<-- logs undefined
};
Because I initialized convo before the fetch and assigned it the value of the data object from the response, I expected that convo would be assigned - especially because logging convo within the .then call was successful.
But it appears it is only valid inside the fetch. I'm probably overlooking something small, so any helpful feedback is very welcome!

Categories