Home > Mobile >  Update object property state inside of watch vue
Update object property state inside of watch vue

Time:10-03

I'm trying to update the selected boolean to true from my lists items array of objects when the from_id property from the items array inside of the entry object matches with the item_id of the object in lists fromData array. The selected property updates but I got this error:

Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] do not mutate vuex store state outside mutation handlers.

store.js

entry: {
    items: [
        {
            from_id: 5,
            to_id: 1,
            quantity: 100,
        },
        {
            from_id: 11,
            to_id: 3,
            quantity: 119,
        },
        {
            from_id: 7,
            to_id: 3,
            quantity: 59,
        },
    ]
}

lists: {
    from: [
        {
            item: {...},
            item_id: 5,
            selected: false
        },
        {
            item: {...},
            item_id: 6,
            selected: false,
        },
        {
            item: {...},
            item_id: 7,
            selected: false,
        }
    ]
}

const getters = {
  entry: (state) => state.entry,
  lists: (state) => state.lists,
};

This what I've tried

computed: { ...mapGetters('Conversion', ['entry', 'lists']),

from: function () {
  return this.lists.from.filter((item) => !item.selected);
},

},

watch: {
    from: {
        deep: true,
        handler: function (items) {
        const _entries = this.entry.items;

        _entries.map((entry) => {
          items
            .filter((item) => item.item_id === entry.item_from_id)
            .map((item) => (item.selected = !item.selected));
        });
      },
    },
},

CodePudding user response:

Vuex is one-way data flow store. You will not able to mutate data directly with the getters, use action/mutation instead. https://vuex.vuejs.org/#what-is-a-state-management-pattern

In your store.js

const store = createStore({
  ...
  mutations: {
    patchEntry (state, payload) {
      // Your logic here => return _entries
      state.entry = Object.assign({}, state.entry, _entries)
    }
  }
})

In your watcher:

watch: {
    from: {
        deep: true,
        handler: function (items) {
            store.commit('patchEntry', items)
        });
      },
    },
},

Ref: https://vuex.vuejs.org/guide/mutations.html#committing-mutations-in-components

CodePudding user response:

The error means what it says. You're mutating the state outside the store. This should happen in mutation/action.

You need to have an action/mutation that modifies the state this way:

mutations: {
  toggle(state, id) {
    let item = state.items.find(item => item.id === id)
    item.selected = !item.selected;
  }
}

And dispatch/commit it outside the store:

this.$store.dispatch('toggle', someId)
  • Related