Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda