Search code examples
javascriptfetch

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


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!


Solution

  • 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.