I’m a rookie at React, I want to exercise what I’ve learnt so far by building a shopping cart application but it throws this error: TypeError: myCart.map is not a function
the related code is here:
1- this is the state of myCart: const [myCart, setMyCart] = useState([]);
2- handler function for adding products to the cart:
function handleAddToCart(product) {
setMyCart( myCart => [...myCart, product]);
setProducts( products.map(prod => prod.name === product.name ? {...prod, quantity: prod.quantity > 0 ? prod.quantity -1 : 0 } : prod));
}
3- passing the handler to ListOfProducts components, then to Product component:
<ListOfProducts products={products} onAddToCart={handleAddToCart}/>
4- passing myCart to Cart component:
{myCart.length > 0 && <Cart myCart={myCart}/>}
5- my implementation of the Cart component:
function Cart(myCart) {
return(
<form className="cart">
<h2>My Cart</h2>
<ul>
{myCart.map((product, index) => (
<li key={index}>
{product.name} - Price: {product.price}
</li>
))}
</ul>
</form>
);
}
the condition in step 4 is working correctly, the Cart component appears whenever I add a product, but when I did console.log(typeof(myCart)) it prints object although the initial state is an empty array. where did I do it wrong?
Edit:
I’ve created a link of the full code in codesandbox
>Solution :
Its a simple mistake with using props:
function Cart(myCart) { //myCart is an object that holds your actual myCart property. (myCart.myCart). It is usually named "props" (props.myCart)
return(
<form className="cart">
<h2>My Cart</h2>
<ul>
{myCart.map((product, index) => ( // in this case, what you need to use is myCart.myCart.map()
<li key={index}>
{product.name} - Price: {product.price}
</li>
))}
</ul>
</form>
);
}
You probably meant to deconstruct the myCard property from props:
function Cart({myCart})
or use it like this
function Cart(props) {
return(
<form className="cart">
<h2>My Cart</h2>
<ul>
{props.myCart.map((product, index) => (
<li key={index}>
{product.name} - Price: {product.price}
</li>
))}
</ul>
</form>
);
}