'TypeError: Cannot read properties of undefined (reading 'map') whole component code is not working
When I start the npm code for the cart component is not working and displayed the blank page map function did not work. When I comment the part which is not working then another component like the header is displayed
import React from 'react';
import Header from './Front/Header/Header';
const Cart = (props ) => {
const {cartitems} =props;
const{handleAddProduct}=props;
const {handleRemoveProduct}=props;
return (
<>
<Header/>
<div className="cart-items">
<div className="cart-items-header"> cartitems</div>
{!cartitems?.length ? (
<div className="cart-items-empty"> No items added in cart</div>
) : null}
<div>
//this part of code is not working
{cartitems.map((item) => (
<div key={item.id}>
<div>
<img className="cart-items-image"
src={item.image}
alt={item.name} />
</div>
<button className='cart-items-add' onClick={()=>handleAddProduct(item)}>+</button>
<button className='cart-items-remove' onClick={()=>handleRemoveProduct(item)}>-</button>
<div className='cart-items-price'>{item.quantity}* ${item.price}</div>
</div>
))}
</div>
</div>
</>
);
}
export default Cart;
here is the code of app.js in this code I got an error that cartitems.find is not a function plz let me know how to fix this issue
const { productitems } = data;
const [cartitems, setCartItems] = useState([]);
const { user } = useContext(UserContext);
const History = useHistory();
const handleAddProduct = (product) => {
// console.log(product);
const ProductExist = cartitems.find((item) => item.id === product.id)
// console.log(ProductExist);
// setCartItems(ProductExist);
if (ProductExist) {
setCartItems(
cartitems.map((item )=> item.id ===product.id ?
{...ProductExist ,quantity:ProductExist.quantity +1}:item)
)
}
else {
setCartItems([...cartitems,{...product,quantity:1}])
console.log('ni gya');
}
}
const handleRemoveProduct = (product) => {
const ProductExist = cartitems.find((item) => item.id === product.id);
if (ProductExist.quantity === 1) {
setCartItems(cartitems.filter((item) => item.id !== product.id));
}
else {
setCartItems(
cartitems.map((item) => item.id === product.id ?
{ ...ProductExist, quantity: ProductExist.quantity - 1 }
: item)
);
}
}
Solution 1:[1]
You can see there is a check above the code you commented out:
{
!cartitems?.length ? (
<div className="cart-items-empty">No items added in cart</div>
) : null
}
It checks to make sure cartitems is an array before attempting to use map() on it. In the ternary statement, instead of returning null if cartitems is empty, you should return the map function so it would read:
{!cartitems?.length ? (
<div className="cart-items-empty"> No items added in cart</div>
) : cartitems.map(item => (
// template code...
))}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chromaloop |
