Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!