Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
how to properly use getters when sorting array

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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!