2

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!

deveb2020
  • 101
  • 2
  • 9
  • 1
    No you can't. Last line of the code will execute before asynchronous code gets a change to initialize `globalData` – Yousaf Feb 13 '21 at 11:48
  • Yes you can store the JsonData but in your code it will execute before asynchronous code gets data so try this, so it don't return undefined setTimeout(() => { console.log( globalData ) }, 4000); – Dpk Feb 13 '21 at 11:51
  • @Yousaf thank you yousaf, do you think there is another way of doing it ? – deveb2020 Feb 13 '21 at 11:51

3 Answers3

2

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.

  • thank you for the explanation, so as i undertand if I want to store it in a global var it is not possible :/ – deveb2020 Feb 13 '21 at 11:57
  • 1
    it is possible, and you do store it correctly, it's just that when you `console.log` it it's not there yet. You need to do all the login from within the callback in `.then` – Antoni Silvestrovič Feb 13 '21 at 11:59
  • 1
    You can also put your whole app in an async function and have your global state there, and just await the fetch function – Antoni Silvestrovič Feb 13 '21 at 12:00
  • 1
    I think this is what i'am going to do, will put tho whole app inside the function fetch so this way i can acces the data at anytime, thank you a lottt – deveb2020 Feb 13 '21 at 12:02
1

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()
Nermin
  • 749
  • 7
  • 17
1

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.

A Ralkov
  • 1,046
  • 10
  • 19