admin 管理员组

文章数量: 1086019

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(";);
  return response.json()
}

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./todos/1");
  return response.json()
}
Share Improve this question edited Apr 25, 2023 at 23:10 Charles Kasasira asked May 26, 2022 at 8:42 Charles KasasiraCharles Kasasira 3201 gold badge5 silver badges17 bronze badges 3
  • 2 If you don't mind me asking, why do you want it in a global variable? Could you consider using a callback where the data is passed as an argument so it can be used by that function or other functions called by that function? – Malekai Commented May 26, 2022 at 8:58
  • On second thought, you could avoid multiple callbacks with arguments and polluting the global namespace by using an IIFE with a data variable at the first level of its scope (like this). – Malekai Commented May 26, 2022 at 9:27
  • dev.to/chovy/… – chovy Commented Jun 9, 2023 at 6:59
Add a ment  | 

3 Answers 3

Reset to default 3

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

I'm new to JavaScript and APIs so the topic to store data from an API fetch call caused some thinking, but I came up with a simple solution that worked for me. I called another function and passed the data to it. Here's my code:

const apiCall = async () => {
    const res = await fetch('https://reqres.in/api/users')
    const data = await res.json()
    displayApi(data.data)
}
    
let email=[]
function displayApi(input){
    input.forEach(element => { email.push(element.email) })
    console.log(email)
}

apiCall()

本文标签: How to store the json data from fetch API request into a global variablejavascriptStack Overflow