1

How to save fetched data into variable in javascript

const SWAPI_URL = "https://random-word-api.herokuapp.com/word?number=10";

let darth = [];

fetch(SWAPI_URL)
    .then(response => response.json())
    .then(darthVaderObj => {
        darthVaderObj
        darth.push(darthVaderObj);

    })

console.log(darth)

1 Answers1

1

The console.log statement is executed before the saving in .then. That's why you will get undefined. This is the expected behavior of asynchronous programming.

Basically, you need to do everything in the .then function in order to have the resolved value of the fetch.

Nolan Edric
  • 406
  • 4
  • 13