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

106
Vistas
La cantidad de productos del carrito no se actualiza cuando se hace clic varias veces

Cuando hago clic en un producto, quiero que la cantidad aumente en 1, la función funciona pero no se muestra en el carrito a menos que agregue otro producto que no existe en el carrito en ese momento. ¿Alguna ayuda?

Lo intenté pero no pude encontrar el error. Creo que el error está en "if(existe){...}" pero no sé dónde.

Lo edité para agregar más código.

 const addToCart = document.querySelectorAll('.addToCart'); let carritoEl = document.querySelector('.ul'); let carrito = []; addToCart.forEach(btn => { btn.addEventListener('click', addToCarritoItem);}); function addToCarritoItem(e){ e.preventDefault(); const boton = e.target; const item = boton.closest('.box'); const itemTitle = item.querySelector('.producto-titulo').textContent; const itemPrice = item.querySelector('.precio').textContent; const itemImg = item.querySelector('.imgCart').src; const itemId = item.querySelector('.addToCart').getAttribute('data-id'); const nuevoProducto = { title: itemTitle, price: itemPrice, image: itemImg, id: itemId, cantidad: 1 }; const existe = carrito.some(item => item.id === nuevoProducto.id); console.log(existe); if(existe){ const producto = carrito.map( item =>{ if (item.id === nuevoProducto.id){ item.cantidad++; return item; }else{ return item; } }); }else{ addItemCarrito(nuevoProducto); } } function addItemCarrito(nuevoProducto){ carritoSumaTotal(); carrito.push(nuevoProducto); renderCarrito(); // } function renderCarrito(){ // carritoEl.innerHTML = ""; // while(carritoEl.firstChild){ carritoEl.removeChild(carritoEl.firstChild) }; carrito.forEach((item) =>{ carritoEl.innerHTML += ` <li class="buyItem"> <img src=${item.image}> <div class="productCartInfo"> <h5 class="prdTitle">${item.title}</h5> <h6>${item.price}</h6> <div class="qnty"> <div> <button class="mbtn">-</button> <span class="countOfProduct">${item.cantidad}</span> <button class="pbtn">+</button> </div> <div><i class="fas fa-times-circle dltProduct" data-id="${item.id}"></i></div> </div> </div> </li> ` }) carritoSumaTotal(); }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Sin registros de errores ni demostración, esto es lo que pienso: es porque no está llamando a la función renderCarrito después de haber incrementado la cantidad:

 // Your Code if(existe){ const producto = carrito.map( item =>{ if (item.id === nuevoProducto.id){ item.cantidad++; return item; // <--- Here you are just returning } else { return item; } }); // <--- You should probably call renderCarrito() after the mapping } else { addItemCarrito(nuevoProducto); }

Aquí hay un fragmento para ayudarlo a entender lo que estoy tratando de explicar:

 if (existe) { // 1. map() would return an array // Since you are updating the array contents, I would // suggest you use forEach() instead, like so: carrito.forEach(item => { if (item.id === nuevoProducto.id) { item.cantidad++; // 2. No need to return item as this would update the item // inside the carrito array directly } // 3. No need of 'else' block // as you are incrementing only if the ids are same }); // 4. Once you are done looping through // you should probably invoke the renderCarrito() method here // unless you want to do anything else renderCarrito(); } else { addItemCarrito(nuevoProducto); }
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