Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda