Search code examples
statevuexstorenuxt.js

Vuex dynamic module undefined state in mutations


I'm trying to troubleshoot a Vue plugin to get it to work with Nuxt. It's using dynamic store modules, and for some reason all the mutations it's using get a state is undefined error.

The basics of it are:

index.js

import mixin from './src/mixin'
import store from './src/store'

export default {
    install: function(Vue, options = {}) {
        options = {
            store: null,
            ...options
        }

        options.store.registerModule('shopify', store)

        // define mixin
        Vue.mixin(mixin)
    }
}

And then the store.js file is basically this:

export default {
    state: {
        product: [],
    },
    mutations: {
        UPDATE_CACHED_RESULT(state, { id, data }) {
            // This is the line that throws a state error
            state.product[id] = data
        }
    },
    actions: {
    }
}

I'm assuming I have the syntax wrong now that this in in a Nuxt setup, but I'm drawing a blank.

Any help?

Thanks!


Solution

  • You should access your store through context property. As stated in Nuxt.js documentation, if you export function, then context will be provided as the first argument of that function. So you can get access to the actual store of your app, and aplly some changes to the store (in your case register module).

    export default (context, inject) => {
      context.store.registerModule("foo", {
        state: {
          id: 1
        },
        mutations: {
          bar(state) {
            state.id = 2;
          }
        }
      });
    }
    

    And then register that plugin in nuxt.config.js:

    plugins: [
      "~/plugins/name-of-your-plugin"
    ]
    

    P.S.: This module registration worked well in my application, but I am not sure about mixin, maybe adding these lines of code could help:

    import Vue from "vue";
    import mixin from "./src/mixin";
    
    Vue.mixin(mixin);
    
    // then export aforementioned function.
    

    Reference.