Ryo Shiina
Ryo Shiina

Reputation: 568

axios GET request works, but can't assign the result contents to a variable

I'm new in javascript/React.js stuff and I've been stuck on this weird issue for 5 hours now :

I'm currently trying to get some data from a database, which sends me a json file whenever I execute my get request with axios. I can get the data and log its contents, but for some reason I can't "forward" anything to the outside of the axios functions.

Here is the short code I wrote, with 2 test logs :

requests.js

foo() {

  // var declared outside of axios function
  var resultSet;

  axios.get(
    /working/url/example/
  ).then((res) => {
    resultSet = res.data.rows.slice();

    // FIRST LOG, inside axios function
    console.log(resultSet);
  }).catch(
    error => console.log(error)
  );

  // SECOND LOG, outside of axios function
  console.log(resultSet);
}

Then I get those weird outputs. somehow, the first log is printed after the second log :

chrome console

undefined                    requests.js:20
(3) [{…}, {…}, {…}]          requests.js:15

The first log successfully shows the contents I requested, but the second log shows that the same variable is somehow undefined.

I'm still new so I might be making a basic mistake, but I've been unable to find any related case to mine on other posts since I couldn't find out what's causing this issue. Any help would be greatly appreciated.

Upvotes: 0

Views: 785

Answers (1)

Wolgan Ens
Wolgan Ens

Reputation: 385

I believe that the reason is the asynchronous request, when you make the GET request, your code keep been executed but the request may be not finished yet, this explains the undefined, and when the request is complete, you get your data printed on the console.

Upvotes: 3

Related Questions