Home > other >  how to properly use getters when sorting array
how to properly use getters when sorting array

Time:11-04

So I'm having problems using vuex getters.

My goal is to sort the cart data which is an array of object by date using getters myCartItems

My problem is that after pushing the second payload {prod_id: 2, date: Wed Nov 03 2021 10:40:20} in my Details component the props['prod_id'] are logging prod_id: 1 instead of prod_id: 2

mutation

addToCart: (state, payload) => {
  state.cart.push(payload) // payload = {prod_id: 1, date: Wed Nov 03 2021 10:37:26}
}

getters

 cartItems: (state) => {
   return state.cart.slice().sort(
      (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
    );
 },

html

  <div v-for="(item,index) in cartItems" :key="index">
       <Details :id="item.prod_id" />
  </div>

CodePudding user response:

Using the index as the key is your problem since the index never changes based on sort order.

The best practice is to use a unique identifier, for example prod_id

<div v-for="item in cartItems" :key="item.prod_id">
  <Details :id="item.prod_id" />
</div>
  • Related