1
votes

I'm having a problem accessing actions in namespaced stores in a Nuxt SPA. Let's say I have a store file in the store directory called "example.js":

import Vuex from "vuex";

const createStore = () => {
    return new Vuex.Store({ 
      state: {
        forms : [],
      },
      mutations: {
        setForms(state, forms) {
          state.forms = forms
        }
      },
      actions: {
        setForms(vuexContext, forms) {
          vuexContext.commit("setForms", forms)
        }
      },
      getters: {
        getForms(state) {
          return state.forms
        }
      }
    })
}

export default createStore;

Then on some page I try to fetch data an put it into the store:

  async fetch(context) {
    return axios.get(..)
      .then(data => {
          context.store.dispatch("example/setForms", data.data) 
      })
      .catch(e => {
        context.error(e);
      });

That gives me:

unknown action type: example/setForms

What am I missing?

2

2 Answers

0
votes

Your example.js is a bit wrong it should look like:

//store/example.js

export const state = () => ({
  forms: [],
});
export const mutations = {
  setForms(state, forms) {
    state.forms = forms;
  },
};
export const actions = {
  setForms(vuexContext, forms) {
    vuexContext.commit("setForms", forms);
  },
};
export const getters = {
  getForms(state) {
    return state.forms;
  },
};

And use it like:

  fetch() {
    return axios
      .get(...)
      .then((data) => {
        this.$store.dispatch("example/setForms", data.data);
      })
      .catch((e) => {
        context.error(e);
      });
  },
0
votes

Please add namespaced: true to your store. So:

const moduleA = { 
      namespaced: true,
      state: {
        forms : [],
      },
      mutations: {
        setForms(state, forms) {
          state.forms = forms
        }
      },
      actions: {
        setForms(vuexContext, forms) {
          vuexContext.commit("setForms", forms)
        }
      },
      getters: {
        getForms(state) {
          return state.forms
        }
      }
}


const store = new Vuex.Store({
  modules: {
    a: moduleA
  }
});


export default store;

so you can use it as $this.store.commit("a/setForms");