Home > Enterprise >  Computed value returns empty array
Computed value returns empty array

Time:12-08

My idea is to render certain buttons inside navigation for certain user role. I have array of this buttons, and each of them has field: permission that is telling what type of permission user have to have to see this button. Then my computed value filters the array returning the buttons that permission is fulfilled with permission of logged in user that I store in vuex.

PROBLEM: When I login and the computed value should return only matching buttons it returns me empty array.

This is my array with buttons:

  public items = [
    { text: 'Strona główna', icon: 'mdi-home', path: '/', permission: [1, 2, 3, 4] },
    { text: 'Znajdź Mecz', icon: 'mdi-map-search', path: '/findGame', permission: [1, 2, 3, 4] },
    { text: 'Niższe Ligi', icon: 'mdi-soccer', path: '/leagues', permission: [1, 2, 3, 4] },
    { text: 'Dodaj Artykuł', icon: 'mdi-file-document-plus', path: '/addArticle', permission: [1] },
  ];

As you can see each role has array of permission of which users can see this button. I am rendering this buttons in a v-for loop:

<v-list-item  v-for="(item, i) in navBarOptions" :key="i" :to="item.path">
    <v-list-item-icon>
        <v-icon large v-text="item.icon"></v-icon>
    </v-list-item-icon>
    <v-list-item-content >
        <v-list-item-title  v-text="item.text"></v-list-item-title>
    </v-list-item-content>
</v-list-item>

And here is computed value (navBarOptions):

  get navBarOptions() {
    const userRole = user.userData?.role.id_role;
    if (userRole != null) {
console.log("Im here"   userRole);
      return this.items.filter((i) => i.permission.includes(userRole));
    } else {
      return this.items.filter((i) => i.permission.includes(4));
    }
  }

When application starts, user is not logged in, so the naavBarOptions return buttons with permission 4 (unLogged User). Then if I login as admin, I can see in this conole.log that my role changed to 1. But in this moment even though this filter looks properly I get empty array.

PS Debuggin: I add small console.log debugging:

if (userRole != null) {
      return (this.items = this.items.filter((i) => {
        i.permission.includes(userRole);
        console.log(i.permission);
        console.log(userRole);
        console.log(i.permission.includes(userRole));
      }));
    } else {

DEBUG CONSOLE

CodePudding user response:

To fix this issue, you can try adding a watch on the user object and update the computed property value when it changes. This way, when the user logs in and the role changes, the computed property will be updated accordingly and the buttons will be filtered properly.

watch: {
  user: {
    handler() {
      this.navBarOptions = this.items.filter((i) => i.permission.includes(this.user.userData?.role.id_role))
    },
    deep: true,
  },
},
  • Related