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
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.
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); }