Search code examples
javascriptvue.jsvue-componentvuexvuex-modules

Not mutate module state in the Vuex store. Vuex | Vue


I'm exploring vuex modules feature and I can't figure out what I do wrong.

I have a simple vuex store with one module.

The module contains a state and mutation option, where just adding a new item in the module state.

When I trying to call the mutation function, it doesn't work.

Codesandbox => https://codesandbox.io/s/currying-fire-2p3eq?file=/src/App.vue


Solution

  • Your action has combined the context and payload arguments into one instead of keeping them separate:

    addItem({ commit }, payload) {  ✅  // Correct
    
    addItem({ commit, payload }) {  ❌  // Incorrect
    

    Another problem is your module's state is an array instead of an object, and is being used directly, as if it was a state item. Make state an object, and put the item data into an array property:

    state: {
      items: [
        { id: "1", name: "1" },
        { id: "2", name: "2" },
        { id: "3", name: "3" }
      ]
    }
    

    Change your computed to use this items property:

    const ItemsState = computed(() => store.state.a.items);
    

    In the mutation, push the new value (what you had before would not change state at all because it just changes the function argument reference):

    SET_NEW_ITEM(state, payload) {
      state.items.push(payload);
    }
    

    You don't need an action to call this:

    function addItem() {
       let newItem = { id: "5", name: "5" };
       store.commit('a/SET_NEW_ITEM', newItem)
    }
    

    Here is your updated sandbox