Search code examples
vue.jsvuejs3vuex

Vuejs_ object returns empty in if condition


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);
  }

Solution

  • 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);
    }