Search code examples
javascriptvue.jsnuxt.jsvuex

Dispatching actions in namespaced stores (Vuex/Nuxt)


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?


Solution

  • 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);
          });
      },