Me sale indefinido porque item de cartitems no está indefinido, ¿cómo puedo solucionarlo?
1.
import React,{useState} from 'react' import {products} from './data' function app() { const [cartitems, setCartitems] = useState([]) const onAddToCart = (product)=>{ const exist = cartitems.find((item)=> { return product.id == item.id }) if(exist){ setCartitems(cartitems.map((item)=>{ item.id == product.id ? {...exist, qnty: exist.qnty + 1}: item })) } else{ setCartitems([...cartitems, {...product, qnty: 1}]) } } return ( <div> {products.map((product)=>( <div key={product.id}> <img src={product.image} style= {{width:"200px"}}/> <p>{product.name}</p> <button onClick={() => onAddToCart(product)}>Add To Cart</button> </div> ))} </div> ) } export default app export const products = [ { id: '1', name: 'MacBook', price: 1400, image: 'https://picsum.photos/id/180/2400/1600', }, { id: '2', name: 'Old Car', price: 2400, image: 'https://picsum.photos/id/111/4400/2656', }, { id: '3', name: 'W Shoes', price: 1000, image: 'https://picsum.photos/id/21/3008/2008', }, ]esto puede solucionar su problema:
1- no devolviste nada del mapa
2- es mejor usar el tipo de función en estado establecido para elementos de carrito
function app() { const [cartitems, setCartitems] = useState([]) const onAddToCart = (product)=>{ const exist = cartitems.find((item)=> { return product.id == item.id }) if(exist){ setCartitems(cartitems.map((item)=> item.id == product.id ? ({...exist, qnty: exist.qnty + 1}): item )) } else{ setCartitems(s=>[...s, {...product, qnty: 1}]) } } En su renderizado inicial, está intentando acceder a una propiedad que no existe. en otras palabras, en su representación inicial, sus products son una matriz vacía
Usar circuitos cortos
{products && products.map((product) => ( <div key={product.id}> <img src={product.image} style={{ width: "200px" }} /> <p>{product.name}</p> <button onClick={() => onAddToCart(product)}> Add To Cart </button> </div> ))}El problema es: no devuelves nada aquí en .map . Es por eso que te estás volviendo undefined .
setCartitems(cartitems.map((item)=>{ item.id == product.id ? {...exist, qnty: exist.qnty + 1}: item })) Simplemente elimine { y } :
setCartitems(cartitems.map((item)=> item.id == product.id ? {...exist, qnty: exist.qnty + 1}: item )) O agregue return explícitamente:
cartitems.map(item => { if (item.id == product.id) { return { ...exist, qnty: exist.qnty + 1 } } return item })