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

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

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 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