Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

303
Visualizações
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()
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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);
})();

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda