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

420
Views
Aumente la cantidad en 1 si el artículo ya existe en el carrito - Reactjs/NextJS

He encontrado muchas preguntas similares al tema, sin embargo, no pude entender la lógica, ya que la mayoría de ellas se preguntan/explican en la comunidad de PHP/MySQL.

Estoy construyendo una tienda de comercio electrónico, donde necesito manejar los artículos del carrito. El problema ya está mencionado en el tema. A continuación se muestra un breve fragmento de mi código.

 // initial state | for testing purpos, I inserted atleast one item hardcoded const [cartItems, setCartItems] = useState([{id: 123, title: 'The Best', price: 55, qty: 1}]) const handleCartUpdate = (id,title, price, qty) => { // first checking if cart is empty or not const cartLength = cartItems.legnth >=1 ? true : false // Check if item exist with the id as given in parameters if(cartLength) { const checkItemExist = cartItems.find(item => item.id == id) // Now, if item exist, update the propert 'qty' , My approach is as under: if (checkItemExist) { cartItems.map(product => { if(product.id == id) { return {product, qty: 2} // for testing purpose, I hard coded qty } } return setCartItems({...cartItems, ...product}) } } else { setCartItems({...cartItems, {...}}) } }

Después de eso, no puedo entender cómo actualizar cartItems

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

La forma estándar de React de actualizar una matriz inmutable sería mapear los elementos, identificar si un elemento necesita o no una actualización y luego devolver el original o una copia actualizada del elemento:

 const [cartItems, setCartItems] = useState([]); const handleCartUpdate = (id, title, price, qty) => { setCartItems( cartItems => cartItems.some(item => item.id === id) ? cartItems.map(item => item.id === id ? { ...item, qty: item.qty + 1 } : item ) : [ ...cartItems, {id, title, price, qty} ] ) }

Si cree que esto es demasiado código repetitivo, piense en usar una biblioteca como Immer para facilitar el manejo de datos inmutables.

about 4 years ago · Juan Pablo Isaza Report

0

Solo necesita filtrar el artículo actual y aumentar la cantidad. A continuación, establezca el valor en el estado. He hecho un trabajo simple aquí. Compruebe si es viable para usted o no.

 const handleCartUpdate = (id,title, price, qty) => { const cartLength = cartItems.legnth >=1 ? true : false if(cartLength) { const checkItemExist = cartItems.find(item => item.id === id) if (checkItemExist) { let currentItem = cartItems.filter(item=> item.id === id); currentItem[0].qty = currentItem[0].qty + 1; setCartItems(...currentItem); }
about 4 years ago · Juan Pablo Isaza Report
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!