I'm trying to implement a shopping cart in React. I've created a context for my cart that handles the quantity purchased and it works fine. However, I have an issue with displaying the data from the cart context to the cart page. Here is my code for the displaying the purchased items to the cart page.
export class Cart extends React.Component {
constructor(props) {
super(props);
}
render(){
return (
<>
<div>
<h1>Cart</h1>
</div>
<CartContext.Consumer>
{
(cartContext) =>{
const {productsToPurchase} = cartContext
console.log(productsToPurchase)
if (productsToPurchase.length === 0){
return(<h1>Cart is empty</h1>)
}
else {
productsToPurchase.map(
(product) =>{
// console.log works fine
console.log("Reached Else Statment")
console.log(product.itemId)
// return doesn't work
return(
<h1 key={product.itemId + "-cart"}> 8525552 </h1>
)
})
}
}
}
</CartContext.Consumer>
</>
)
}
}
I have done the same thing and it worked. I have no idea why my mapping function doesn't display the data that I need. Check the comments please for more details
You are missing a return. You should return the result of productsToPurchase.map()
<CartContext.Consumer>
{
(cartContext) =>{
const {productsToPurchase} = cartContext
console.log(productsToPurchase)
if (productsToPurchase.length === 0){
return(<h1>Cart is empty</h1>)
}
else {
return productsToPurchase.map(
(product) =>{
// console.log works fine
console.log("Reached Else Statment")
console.log(product.itemId)
// return doesn't work
return(
<h1 key={product.itemId + "-cart"}> 8525552 </h1>
)
})
}
}
}
</CartContext.Consumer>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.