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

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