Search code examples
javascriptarraysvue.jsvuejs2vuex

How to update a state array in Vuex?


I need to be able to ADD, REMOVE AND EDIT entries. So far I've only been able to add and remove.

My question is: to add, use PUSH, to remove, use SPLICE. But what about editing?

I am working with VUEJS, VUEX and JavaScript.

Example of what I'm doing:

<b-button type="submit" @click.prevent="submit()">SAVE</b-button>

methods: {      
  submit() {
    this.$v.edit_category.$touch();
    if(this.$v.edit_category.$error) return
    this.editCategory()
  },
  editCategory() {
    const category = {
      value: this.edit_category.value,
      text: this.edit_category.text,
      category_active: this.edit_category.category_active,
    }        
    
    this.$store.commit('saveCategory', category)
  },
},

store.js:

actions: {
addCategory({ commit }, payload) {
  console.log(payload)
  commit('addCategory', payload) 
},
saveCategory({ commit }, payload) {
  console.log(payload)
  commit('saveCategory', payload) 
},
 deleteCategory({ commit }, payload) {
  console.log(payload)
  commit('deleteCategory', payload) 
}


mutations: {
addCategory(state, category) {   
  state.categories.push(category)      
},
saveCategory(state, payload) {
  state.categories.push(payload)
},
deleteCategory(state, category) {
  var index = state.categories.findIndex(c => c.value === category.value)
  state.categories.splice(index, 1)
},

Solution

  • Use Vue.set:

    import Vue from 'vue';
    // ...
    
    editCategory(state, category) {
      var index = state.categories.findIndex(c => c.value === category.value);
      Vue.set(state.categories, index, category);  // ✅ Vue.set
    },
    

    This is needed because reading the docs we see:

    Vue cannot detect the following changes to an array:

    When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue