Home > Enterprise >  Vuejs_ object returns empty in if condition
Vuejs_ object returns empty in if condition

Time:12-12

I am trying to give the user certain permissions, but I am unable to access the teamsList object which shows empty in the 'if condition'

output console

output console

please check this image. The if-condition is not working.

async created() {
  console.log('teams list is before loading teams',this.teamsList);
    this.loadTeams()
      .then((response) => {
        this.teamsList = response.data;
         console.log('teams list is after loadteams',this.teamsList);

      })
      .catch((error) => {
        console.log(error);
      });
      
      if (this.teamsList.teamName==='admins') {
      this.haveAccess=true
      console.log('access-check',this.teamsList.teamName);
    } 
  console.log('access-check', this.haveAccess,this.teamsList);
  }

CodePudding user response:

Put if condition inside .then method, also you can remove async as you are not using await

  created() {
      console.log('teams list is before loading teams',this.teamsList);
      this.loadTeams()
      .then((response) => {
        this.teamsList = response.data;
         console.log('teams list is after loadteams',this.teamsList);
         if (this.teamsList.teamName==='admins') {
           this.haveAccess=true
           console.log('access-check',this.teamsList.teamName);
         } 
         console.log('access-check', this.haveAccess,this.teamsList);
      })
      .catch((error) => {
        console.log(error);
      });
  }

CodePudding user response:

An object's property can not be access directly if it is inside an array.
In your code, the teamsList variable is an array which is holding 3 items. Therefore, you can not access the property teamName directly on that array.

If your data is dynamic then you need to loop on each time to access its property teamName.

this.teamsList.forEach(item => {
  if (item.teamName === 'admins') {
     this.haveAccess=true;
     console.log('access-check', item.teamName);
  }
})

If your data is fixed which means always an array of 3 items with fixed data then you can access it like this-

if (this.teamsList[0].teamName === 'admins') {
   this.haveAccess=true;
   console.log('access-check', this.teamsList[0].teamName);
}
  • Related