简体   繁体   中英

How to store the json data from fetch API request into a global variable - javascript

I have been working with the fetch API and got the data logged to the console successfully from the then() but I am looking for a way to put this data in a global variable that I will use later. I was able to do this with reactjs because of its state management but in vanilla javascript, it is hard to do due to the promise returned

Things I have tried

const res = await fetch('./data.json')
    .then(res => res.json())
    .then(data => data) // when I log from here I get the data but can't assign it to a global variable even tried using `var`

using async/await still no hope.

const fun = async () => {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  return response.json()
}

Inside an asynchronous function getData which fetches the remote data, you can get the parsed JSON body as a JavaScript object and assign it to a variable dataGlobal defined in the global context.

Of course, you have to wait for getData to execute before dataGlobal is declared. Therefor, I'm using an asynchronous IIFE .

 let dataGlobal; const getData = async () => { const response = await fetch("https://jsonplaceholder.typicode.com/todos/1"); const data = await response.json(); dataGlobal = data; return data; }; (async () => { await getData(); console.log(dataGlobal); })();

While I understand that you'd like a global variable for your data, I would advise against polluting the global namespace (see also: [1] , [2] , [3] and [4] ).

You could instead encapsulate everything in an Immediately Invoked Function Expression (IIFE) , and have your fetch method inside of it with all of the code related to that area of your program.

Then, by rearranging @alexanderdavide's answer , we get the following code:

(async () => {
  let data_local;

  const getData = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    const data = await response.json();
    dataGlobal = data;
    return data;
  };

  await getData();
  console.log(data_local);

  // your code goes here...
})();

You could also use the following alternative as well:

(async () => {
  const getData = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    const data = await response.json();
    dataGlobal = data;
    return data;
  };

  let data_local = await getData();
  console.log(data_local);


  // your code goes here...
})();

That way your data_local variable would be available to everything beneath it but not outside of the IIFE itself, protecting the global namespace while allowing multiple methods access to the same variable without using callbacks with a data argument.

NOTE: please be careful if/when you change the data variable, you might end up changing it multiple times and inadvertently causing an error because of missing / improperly formatted data.

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM