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

171
Vistas
why is my onclick function not working on the first click?

I'm creating a sneaker store where I have an add to cart function,

first, when the add to cart is clicked it updates the size that's selected second it adds the changed item,

object into the cart State the problem is that on the first click there is no object returned but

every time after the first click it returns the data.

this is the function that updates the size:

 const updateSelectedSize=(item,selectedSize)=>{
        item.size=selectedSize;
        return item;
    
      }

here is the function that I use to add the updated item to the cart:

const handleAddtoCart=(item,selectedSize)=>{


 const  updatedItem=updateSelectedSize(item,selectedSize);
 

 let  newitemArray=[...cart,updatedItem]
  setcart(newitemArray)


console.log(cart);
 

 }

here is the component that executes the function on click:
<i onClick={()=>{handleAddtoCart(product,selectedSize)}}className="fa-solid fa-cart-arrow-down"></i>

here is the console.log of the first click: enter image description here

and here's the console log of the second click: enter image description here

as you can see nothing happens on the first click I'm thinking this is has something to do with the useState cart variable and the spread operator the initial value for it is:

 const [cart, setcart] = useState('');

I've tried to set the value to different things such as an empty array but it always gives the same result.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Because you write your console.log(cart) inside the handleAddtoCart and your state not updated yet.

if you move console.log(card) outside of handleAddtoCart function, you can see the result is work perfectly.

And for empty array it is better to use

✅  const [cart, setcart] = useState([]);

instead of this one

❌  const [cart, setcart] = useState("");

Full code is here

export default function App() {
   const [cart, setcart] = useState([]);

   const updateSelectedSize = (item, selectedSize) => {
   item.size = selectedSize;
   return item;
};

const handleAddtoCart = (item, selectedSize) => {
   const updatedItem = updateSelectedSize(item, selectedSize);
   let newitemArray = [...cart, updatedItem];
   setcart(newitemArray);

   console.log("STATE NOT UPDATED YET", cart);
};

 console.log("STATE UPDATED", cart);

 return (
   <div className="App">
      <i onClick={() => { handleAddtoCart({ size: 3 }, 2) }}>
       CLICK TO SET
     </i>
   </div>
 );
}

Best.

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