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

109
Visualizações
spread operator returning empty array of objects on first click

for my eCommerce store im making an add to cart functionality, here is what the store looks like : enter image description here

the issue I'm having is when I click add to cart I have an on-click function that takes the item object and selected size and first it updates the selected size then it sets the item in the cart the function looks like this.

     const [cart, setcart] = useState('');
// this is the state that i use to add the cart items into
      const handleAddtoCart=(item,selectedSize)=>{

     let updatedItem=updateSelectedSize(item,selectedSize);
// updated size
     
     setcart([...cart,updatedItem])
     
     console.log(cart);
    
      }
      const updateSelectedSize=(item,selectedSize)=>{
        item.size=selectedSize;
        return item;
// function to update the selected size in the the item object
    
      }

this is the component that i pass the add to card function to:

 <ShoeProductCard productData={productData} handleAddtoCart={handleAddtoCart} />

here is the component that the onclick function has been passed down to :

`<i onClick={()=>{handleAddtoCart(product,selectedSize)}}className="fa-solid fa-cart-arrow-down"></i>`

now this all works fine except for one thing the first time that the button is clicked this is what logs on the console: enter image description here

now the second time I click I get the data that I need: enter image description here

I know the problem is with the spread operator and the initial value of the cart state which is causing it to return empty. I've tried to set the initial state to different values but anything but an empty array and empty quotes seem to break the code. I just want a way I can store every time someone clicks on the add to cart function in the cart state variable.

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