Cannot access vuex mutation in dynamically registered module

Viewed 215

I have created a module to grab api data and hold it for a vue component:

import Vue from 'vue';

export default {
    namespaced: true,

    state() {
        return {
            all: []
        }
    },

    getters: {
        all(state) {
            return state.all;
        }
    },

    mutations: {
        all(state, data) {
            Vue.set(state, 'all', data);
        },

        clear(state) {
            Vue.set(state, 'all', []);
        }
    },

    actions: {
        async init({ commit, state }) {
            let response = await this.axios.get('/api/v1/teams/', {
                params: {
                    includes: 'users'
                }
            });

            if (response.status === 200) {
                let data = response.data.data.filter(function (element) {
                    return element.users.length > 0;
                });

                commit('userTeamSelect/all', data, {root: true});
            } else {
                Vue.toasted.error('Could not fetch team data', {
                    duration: 10000
                });
            }
        }
    }
}

I have a component that is dynamically registering the module when it is created and removing the module from the store before it is deleted:

created() {
    if (this.$store.getters['userTeamSelect/all'] === undefined) {
        this.$store.registerModule('userTeamSelect', UserTeamSelectModule);
        this.$store.dispatch('userTeamSelect/init');
    }
},

beforeDestroy() {
    if (this.$store.getters['userTeamSelect/all'] !== undefined) {
         this.$store.commit('userTeamSelect/clear');
         this.$store.unregisterModule('userTeamSelect');
    }
},

When I navigate to a page where this component is used, I get the following error message in the console: [vuex] unknown mutation type: userTeamSelect/all

This mutation is only called within the init action of the dynamic module, so the problem must be there somewhere. I have tried calling it both locally commit('all', data) and globally commit('userTeamSelect/all', data, {root:true}) with no luck.

The module must have been added to the vuex store because I can call the action without issue. It just seems the mutation isn't being registered somehow? I would expect it to work fine, or recieve an error about an unknown action.

Can anyone point me in the right direction please?

0 Answers
Related