[Vuejs]-Vuex: Return getter in mounted hook

4👍

Watch the computed, and then execute the code once the user role is set, for example:

computed: {
    ...mapGetters('user', {
      user: 'getUser',
      userRole: 'getRole',
    })
},

watch: {
    userRole: {
        handler(role) {
             if (role) {
                 this.yourAction();
             }
        },
        immediate: true
    }
},

methods: {
    yourAction() {
        console.log('got role:', this.userRole);
    }
}

The immediate property is used within the watcher for userRole so that the handler will be called immediately when the component is loaded.

👤Rich

1👍

Since both routes need the same data, and the user can pretty much decide what route to access first — you might want to initiate the API call in both routes, only adding a flag to it whether or not the specific call has already been initiated by other routes.

In your store states, you can define some sort of collection that holds boolean properties.

api_calls_ok: {
    user_data: false
}

Then you can define an action that does similar to this

const userToken = localStorage.getItem('token'); //side note: you can use localStorage.token instead
await this.getUserRole(userToken);
await this.getUserImage(userToken);

Maybe something like

getUserData({ commit, state }){
    if(!state.api_calls_ok.user_data){
        dispatch('getUserRole');
        dispatch('getUserImage');
        commit('flagApiCalls', 'user_data', true); //set the boolean to true
    }
}

In App.vue and Project.vue, you can just dispatch the getUserData during mount and not worry about calling the API twice or more. After dispatching, just access your getter.

Leave a comment