1

I have a problem, I'm trying to get my room data from my API to use the map function after but I can't get the data. Here is my code.

    Axios.get(`/user/rooms?${token}`).then(res => {
        tmp.push(res.data)
    })
    const data = tmp
    const Rooms = [data]
    const RoomNames = []

And Here is the output after making console.log(data):

0: (4) [{…}, {…}, {…}, {…}]length: 1
__proto__: Array(0)

And data[0] is undefined​

Renaldo Balaj
  • 2,390
  • 11
  • 23
Ghellab
  • 13
  • 2
  • 1
    Welcome to Stack Overflow! Have a look at [writing the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question). What have you investigated? – Jeroen Heier Dec 02 '19 at 17:30
  • Please provide the code that is causing the problem. There must be some small problem between you doing `console.log(data)` (and it works) and you doing `data[0]` (and it doesnt). Also check if the data has `undefined` in it, but that should not be abbreviated to `{...}` by the output.... – Jessie Koffi Dec 02 '19 at 17:30

2 Answers2

0

Javascript is based on asynchronous so the only way to do this is to call all your logic inside the callback (because .then needs more time, and javascript doens't wait for it)

Axios.get(`/user/rooms?${token}`).then(res => {
    tmp.push(res.data)
    // this comes later so you can only get res.data in here
    const data = tmp
    const Rooms = [data]
    const RoomNames = []
})
// everything under here will be executed before .then
Renaldo Balaj
  • 2,390
  • 11
  • 23
0

Axios.get is a promise, which will get added to the event loop for execution. .then will act as a callback after data from your request is ready it will get executed.

In your code, you are accessing tmp to data before data from the request is added to tmp array.

let tmp = [];

Axios.get(`/user/rooms?${token}`).then(res => {

    tmp.push(res.data);
    const data = tmp
    const Rooms = [data]
    const RoomNames = []

})

For more about promises.

Akshay Bande
  • 2,491
  • 2
  • 12
  • 29