0

I am getting data from an API. I need this response data to use outside of axios, not inside any function but globally available in JavaScript, HTML DOM.

let responseData = [];
axios
.get(url)
.then(res => {
 responseData.push(res.data.data);
});

console.log(responseData);

console.log(responseData); gives the output:

[]

inside this array is another array of objects [{},{},{}]

[[{},{},{}]]

But the format I need is [{},{},{}]

Any idea how should I approach this?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    var whatYouWant = responseData[0]; – Pal Singh Nov 08 '19 at 06:17
  • Also, console log will log empty array because it is outside of `then`. Only after the call is successful, it will be populated [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321) – adiga Nov 08 '19 at 06:22
  • var whatYouWant = responseData[0] | This giving undefined. already try this. – Cobra Commander Nov 08 '19 at 06:25
  • I know that works inside the then(() => { // here }). I want to use outside the then, Also I don't want to pass the result to another function. The data needs to accessible globally. The data retrieve we can also assign as const. Thanks for trying to help really appreciated. – Cobra Commander Nov 08 '19 at 06:44

1 Answers1

-1

try in this way:

responseData=responseData.concat(res.data.data);