Search code examples
javascriptvue.jsvue-componentnuxt.jsvuex

Nuxt store mutation recieving TypeError


I set up a simple store in store/index.js that looks like this:

export const state = () => ({
    isDark: false,
});

export const mutations = {
    setIsDark(state, payload) {
        state.isDark = payload;
    },
};

export const getters = {
    getIsDark(state) {
        return state.isDark;
    },
};

I'm able to get isDark in my component but when I try to call setIsDark I get a error:

TypeError: Cannot read property 'setIsDark' of undefined

My component:

computed: {
    isDark() {
        return this.$store.getters.getIsDark;
    },
},

methods: {
    toggleIsDark() {
        this.$store.mutations.setIsDark(!this.isDark);
    },
},

What am I doing wrong?


Solution

  • The syntax for calling a mutation is:

    this.$store.commit('setIsDark', !this.isDark);
    

    For an action, it's:

    this.$store.dispatch('setIsDark', !this.isDark);