Id like to store my data inside of a variable vs passing it through functions after fetching from json file. example: I am able to log my array of 5 objects. Now I want to see if I can assign the data (my array) to a variable called q1obj. How can I do this?
Where did you define the variable
data? I see you used the name
data in the
then method of the
fetch. But in that instance you are just naming a function parameter. You aren’t actually defining a variable that can be used somewhere else.
Ok, so here I have defined a variable above the fetch… I then try assigning it to data within the fetch… I log to see if the ‘test’ varible holds the contents from data, but error.
Ok so i was able to push the data into my global scoped variable ‘test’. I was missing the empty array. But I still have a problem. Even though it logs all of my data, I now want to try to store only one of my objects instead of all.
hello and welcome back to fcc forum
according to this error message you are trying to “access” an object value which isnt “ready or found” to do that operation…
also always post and share (when possible editable) code, that way its more useful, happy learning
Thanks, good to be back and will do!
After some research last night it seems like I can only use fetched data within functions, passing from one function to the next vs simply storing it inside of a variable because I would need either async, await, promises. I am unfamiliar with these terms and it is still hard to grasp.
I wish there was a simple way to just assign a variable to fetch and then use it everywhere globally to assign more variables. This is how I want it to happen (below):
Except that these lines of code:
let nameOfFrank = data.name let nameOfBob = data.name let HobbyOfBob = data.hobby
Will execute before the
fetch has completed and thus unless you already have the
data array pre-filled with data before the
fetch is done then the
data array won’t have anything in it. In other words, you can’t use
data until the
fetch has completed. That’s the nature of asynchronous JS.
What you could do, instead is call a function in that last
then method and pass in the data you get from
fetch and then do something with the data in that function.
Or you could use
await on the
fetch call to make the code act more like you want it to.
But if you don’t understand asynchronous JS to begin with then I would suggest you start by reading up on that first.
thank you, yes I got it to work using a function. I think I will start diving into asynchronous. It’s been on the list.
- data.name is undefined!! or worse “uncaught error”
can you see why is that?