0

I cannot figure out how to get data from a fetch response into a new global variable. I am using this question but I don't want to console.log() the array, but instead put it into a new variable.

Using the linked question, I am doing almost the same:

function getvals(){
  return fetch('https://jsonplaceholder.typicode.com/posts')
  .then((response) => response.json())
  .then((responseData) => {
    return responseData;
  })
}

let data;
getvals().then(response => {
  data=response;
})

I would like the data variable to hold the array that is return. I thought I would just have to declare a new global variable and then change within the .then but I get undefined.

Yolo_chicken
  • 1,221
  • 2
  • 12
  • 24
  • I just ran your code and can access `data` globally, where are you trying to access it from? maybe there's another `data` variable somewhere, in the arguments or something? – Cagri Sep 14 '22 at 18:09
  • When are you checking to see if `data` is set? `getvals()` returns a promise, and code execution does not wait for the `.then()` to execute. If you're trying to get the value of the variable directly after the `getvals()` call, it will be undefined because the `fetch` request hasn't finished yet. You need to either await it or use a callback within the `then()` – Jesse Sep 14 '22 at 18:10
  • @Jesse where would I place the await? Sorry, fairly new to JS – Yolo_chicken Sep 14 '22 at 18:15
  • @Yolo_chicken if you want to use await use this code `async function getvals() { const response = await fetch("https://jsonplaceholder.typicode.com/posts"); const responseData = await response.json(); return responseData; }` but I don't think is necessary, if you want here the code refactored – Laaouatni Anas Sep 14 '22 at 18:17

1 Answers1

1

Run your code in an async function.
Because of the nature of Promises you can't break the promises outside of an asynchronous flow. Learn more about Using Promises and the async/await syntax to become familiar with the concepts. They're a game changer.

function getvals(){
  return fetch('https://jsonplaceholder.typicode.com/posts')
    .then((response) => response.json());
}

async function main() {
  const data = await getvals(); // Waits here until getvals() is done.
  console.log(data);
}

main();
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
  • I'm getting `Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules`. I tried adding `async` in front of `function getVals(){}` but same error. – Yolo_chicken Sep 14 '22 at 18:54
  • 1
    Ah yes, I've misread that top-level `await` only works in modules. – Emiel Zuurbier Sep 14 '22 at 18:58
  • Instead of outputting `data` in `console.log`, I would like it set as a global variable. I've tried `let data;` above `main()` and removing `const`, but no luck. Still getting `undefined`? – Yolo_chicken Sep 14 '22 at 19:17
  • 1
    I know you would like that, but that's not how Promises work. You have to *wait* before `getvals()` continues, and the only way to do that is **inside** the scope of an *async function* or in the callback function of the promises's `then` method. – Emiel Zuurbier Sep 14 '22 at 19:21