Mfdsix Indo
Mfdsix Indo

Reputation: 23

How to get the array value from axios response

I am stuck for 4 hours for facing this problem. I have this code

var sttr = [];
      this.$http
      .post(this.api_url+url, data)
      .then((response)=>{
        sttr.push(response.data);
      })
      .catch((error)=>{
        if(error.request.status == 401){
          this.unauth();
        }else{
          sttr.push(error.response.data.errors);
        }
      });
      console.log(sttr[0]);

My response from both success and error is stored to the sttr variable. But the problem is when i want to get the first value of array, it's return undefined value. So, is there any solution for this problem ?

Upvotes: 0

Views: 1135

Answers (2)

sdn404
sdn404

Reputation: 624

execute the console.log(sttr[0]) inside 'then' callback will work i think. As you said in the comment that, console.log(sttr) is working, You can create a condition in the last part of your code.

if(sttr.length) {
  console.log(sttr[0]);
}

Upvotes: 0

Andy Carlson
Andy Carlson

Reputation: 3909

You are actually calling console.log(sttr[0]); before the response comes back, because this code is async. You need to log it inside the then callback to ensure it happens after the response is received.

Upvotes: 1

Related Questions