Dave
Dave

Reputation: 2018

How do I remove an item from basket with state management?

This is my store file. I have set up adding items to basket, now I would like to remove item from basket when button is clicked 'Remove from basket' in another component. How do I solve this?

state: {
  basketItems: []
},
mutations: { 
  [ADD_TO_BASKET](state, value) {
    state.basketItems.push(value);
  }
},
actions: {
  addToCart({ commit }, value) {
    commit(ADD_TO_BASKET, value);
  }
},

Basket component

computed: {
  ...mapState({
    basketItems: state => state.basketItems
  }),
  sumUpItems() {
    return this.basketItems.reduce(
      (acc, basketItem) => acc + parseFloat(basketItem.price),
      0
    );
  },
  basketCount() {
    return this.basketItems.length;
  },
}

Upvotes: 0

Views: 239

Answers (1)

Phil
Phil

Reputation: 164776

Add another mutation that removes a basket item using either Array.prototype.filter() or Array.prototype.splice()

mutations: {
  [ADD_TO_BASKET]: (state, value) => {
    state.basketItems.push(value)
  },
  [REMOVE_FROM_BASKET]: (state, item) => {
    // splice version
    const index = state.basketItems.indexOf(item)
    if (index >= 0) {
      state.basketItems.splice(index, 1)
    }

    // or

    // filter version
    state.basketItems = state.basketItems.filter(basketItem => basketItem === item)
  }
}

Then, say you have a component that iterates all items, you can add a button to remove one

<!-- just guessing on the "id" property for the "key" attribute -->
<div v-for="item in $store.state.basketItems" :key="item.id">
  <button @click="$store.commit('REMOVE_FROM_BASKET', item)">Remove</button>
</div>

You'll probably want to use mapState, mapMutations, mapActions, etc but hopefully you get the idea.

Upvotes: 1

Related Questions