Search code examples
javascriptvuejs3vuex

The filter function does not remove the object in the array in Vue/Vuex


I am busy with making a booking function in vue3/vuex. A user can book an item and also remove it from the basket.The problem is that the Filter function in vue does not remove the object in the array and I can not find out what the problem is. I hope you can help me

This is the result if I put console.log() in the removeFromBasket(state, payload)

removeFromBasket(state, payload) {
        console.log('removeFromBasket', payload, JSON.parse(JSON.stringify(state.basket.items)))
    }

enter image description here

  • method to remove
removeFromBasket() {
      this.$store.commit('basket/removeFromBasket', this.bookableId);
}
  • basket module
const state = {
    basket: {
        items: []
    },
};

const getters = {
    getCountOfItemsInBasket: (state) => {
        return state.basket.items.length
    },
    getAllItemsInBasket: (state) => {
        return state.basket.items
    },
    inBasketAlready(state) {
        return function (id) {
            return state.basket.items.reduce((result, item) => result || item.bookable.id === id, false);
        }
    },   
};

const actions = {};

const mutations = {
    addToBasket(state, payload) {
        state.basket.items.push(payload);
    },
    removeFromBasket(state, payload) {
        state.basket.items = state.basket.items.filter(item => item.bookable.id !== payload);
    }
};

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
};

enter image description here


Solution

  • I have solved the problem. I used typeof() in console.log() to see what type the payload and item.bookable.id are. The payload was a string and the item.bookable.id was a number. So I put the payload in parseInt(payload) and the problem was solved.

    removeFromBasket(state, payload) {
       state.basket.items = state.basket.items.filter(item => item.bookable.id !== parseInt(payload));
    }