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

209
Views
Pushing empty array using useState in React

I've been working on an e-commerce website and when i click on an item to get it into the car, i've created a function to push the element into a Car array.

const getItem=(id) =>{
        const product=products.find(item =>
            item.id === id)
            return product;
    }
   
    const addToCart=(id)=>{
        let tempProducts=[...products]
        const index=tempProducts.indexOf(getItem(id))
        const product=tempProducts[index];
        product.inCart=true;
        product.count=1;
        const price=product.price;
        product.total=price;
        setCart([...cart,product]);
        setProductos(tempProducts);
        console.log(cart)
    }

The problem that i got is when i clicked to the first element to go into the Cart array it pushes an empty value, but when i clicked the second item, it brings me the previous array that i clicked.

I don't know what happens with the index but if you know about it, please tell me

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!