0

Ok, so I am trying to up-skill my self with ES6 JS, but I am using the Axios plugin to get data from an API.

However I can not seem to access the data outside of the then call from Axios,

let testData = {};

axios.get(URL, {headers: {Authorization: `Bearer ${TOKEN-HERE}`}}).then((res) => {
    testData = res.data;
});

console.log(testData); <- this is still empty?

So as far as I understand, the arrow function was meant to keep the context the same? so I dont have to do anything like let self = this to assign data from Axios into my data var?

But if I console.log(testData) within the Axios get call, it returns my data?

So what am I doing wrong? And how do I get data out of that Axios call?

Please help?

C0ol_Cod3r
  • 909
  • 2
  • 15
  • 35
  • console.log(res.data); before testData = res.data; – Jackkobec Sep 06 '19 at 20:08
  • that will show the same as what the testData shows? There is data (json format) coming from my api. – C0ol_Cod3r Sep 06 '19 at 20:09
  • There's nothing wrong with the scope of your variables or the arrow function. What you didn't take into account is that fetching is asynchronous. And no, you cannot get data out of the future, you need to take the work that relies on the data (i.e. logging it) into the future. – Bergi Sep 06 '19 at 20:17
  • I dont understand, nor did I get anything from that other questsion. I now its async. but that does not tell me how to fix or force it to load the data correctly? – C0ol_Cod3r Sep 06 '19 at 20:22

0 Answers0