Search code examples
javascriptarraysvue.jsvuexvuex-modules

Can't remove an item from an array Vuex


Having tried all the methods that I found here (including this.$delete), I cannot remove an item from the array.

findIndex and IndexOf return -1, apparently therefore do not work. filter or splice doesn't work either.

I suspect that I am doing something wrong. I will be grateful for the help

Vuex

  namespaced: true,
  state: {
    coefficients: [],
  },
  mutations: {
    getDataState(state, coefficients) {
      state.coefficients = coefficients;
    },
    itemDelete(state, item) {
      const index = state.coefficients.findIndex((el) => el.id === item.id);
      if (index > -1) state.coefficients.splice(index, 1);
      // #2 state.coefficients.splice(index, 1);
      // #3 
      /* const index = state.coefficients.indexOf(item);
      console.log(index, 'index');
      if (index > -1) {
        state.coefficients.splice(index, 1);
      } */
    },
  },
  actions: {
      getData({ commit }, userData) {
      api.get('/coefficients/')
        .then((res) => {
          commit('getDataState', {
            coefficients: res,
          });
        })
        .catch((error) => {
          console.log(error, 'error');
          commit('error');
        });
    },
      deleteData({ commit }, { id, item }) {
      api.delete(`/coefficients/${id}`)
        .then((res) => {
          commit('itemDelete', {
            item,
          });
          console.log(res, 'res');
        })
        .catch((error) => {
          console.log(error, 'error');
        });
    },
  },
}; 

Component

        <div v-for="(item, index) in this.rate.coefficients" :key="item.id">
          <div>{{ item.model }}</div>
          <div>{{ item.collection }}</div>
          <div>{{ item.title }}</div>
          <span v-on:click="deleteItem(item.id, item)">X</span>
         </div>
         
        /* ... */

         methods: {
          deleteItem(id, item) {
            this.$store.dispatch('rate/deleteData', { id, item });
            },
        },
         created() {
          this.$store.dispatch('rate/getData');
        },


Solution

  • Your itemDelete mutation expects an object with an id property, but you are passing it an object with an item property, because you are wrapping item in a plain object while passing it.

    Change the commit in deleteData to pass the item without wrapping it first:

    commit('itemDelete', item);