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

106
Views
My else part of add to cart functionality is also putting the new quantity in the cartItems array rather than just increasing quantity of Items

cartItems is a state array that contains the items that user adds and the logic that I have used is that if the item already exists in the cart then increase its quantity else put the quantity to 1.

const [cartItems,setCartItems]=useState([])
  
  const handleAddItem=(item)=>{
     if(!cartItems.find(product=>product.id===item.id)){
        setCartItems([...cartItems,{...item,quantity:1}])
     }
     else{
       setCartItems([...cartItems,
        cartItems[cartItems.findIndex(product=>product.id===item.id)]
        .quantity++])
     }
  }

After adding a item 5 times to the cart I'm getting following result but I only want object inside the array and not other elements.

 [Object, 1, 2, 3, 4]
0: Object
id: 1
name: "Sunday"
price: 100
quantity: 5
1: 1
2: 2
3: 3
4: 4
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Figured out the code below can be used in else condition

else{
cartItems[cartItems.findIndex(product=>product.id===item.id)].quantity++
      setCartItems([...cartItems])
}
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!