Home > Net >  Cannot read value from axios GET request response outside of axios function
Cannot read value from axios GET request response outside of axios function

Time:09-24

I am trying to create a task tracker. BackEnd is mySQL, API is built using Node JS and Express JS and frontend is React JS.

I am trying to assign a variable the response I get from the GET request.

the request works in PostMan

In my frontend I am trying to assign the variable using the following code. As shown above, the get request works in PostMan.

Code

const baseURL = 'http://localhost:5000/api/user/timesheet/13009';
let y = [];

axios.get(baseURL).then((response)=>{
   for( var i in response.data){
    y.push( response.data[i]);
   }
   console.log(y);

});

Output

This is the output at the terminal. I can use indexes like y[0] and get that particular value. But when I remove the print statement and place it below the code, value of y changes.

const baseURL = 'http://localhost:5000/api/user/timesheet/13009';
let y = [];

axios.get(baseURL).then((response)=>{
   for( var i in response.data){
    y.push( response.data[i]);
   }
   

});

console.log(y);

Secound Output

I get this output but y.length is set to 0 and I cant read the data in y.

const baseURL = 'http://localhost:5000/api/user/timesheet/13009';
let y = [];

axios.get(baseURL).then((response)=>{
   for( var i in response.data){
    y.push( response.data[i]);
   }
   

});

console.log(y);

console.log('y.length');
console.log(y.length);
console.log('y[0]');
console.log(y[0]);

Third Output

This is showing that there is no value for the index and the array is empty. What exactly is causing this issue and how can it be fixed?

CodePudding user response:

I think it's because the works that you set in "then()" is executed after the axios request worked, when your data has been successfully recovered. The code after the axios call (a promise) is executed before / in same time as the promise, meaning that the data has not been already recovered.

CodePudding user response:

like @Nevermore1803 said, axios will return ur request after some amount of time.

So must likely your array y that you are pushing the values from axios to, still haven't been populated by the time axios has it answer from the request.

you can see it by urself by doing the following

axios.get(baseURL).then((response)=>{
   for( var i in response.data){
    y.push( response.data[i]);
   }
   
console.log('1')
});

console.log('2')

You can see that 1 will come after 2, so in order to work with your array, before you try to using him, you need to check if he is already populated and then proceed to work with him.

One way to check if ur array is empty is >> if(array.length > 0){... do something}

Also, if you are using react you should start using its hooks, like useState to work with data like this.

  • Related