I am trying to make a shopping cart and I want to add a counter into the header but I get an error that says "Cannot read property 'length' of undefined".
This is the code for the header:
import React,{useState} from 'react';
function Toolbar(props){
const {cart} = props;
return(
<header>
<button>
<span>
Go To Cart:
{cart.length}</span>
</button>
</header>
)
}
export default Toolbar;
And this is the code for the products page. It does count in the console log but not on the screen.
import React, {useState} from 'react'
function Products(props) {
const [cart, setCart]=useState([]);
const addtoCart=(props)=>{
console.log('we are in addToCart');
setCart([...cart,props]);
};
return(
<div >
<h1>Products</h1>
<div className="product" key={props.id}>
<h3>{props.name}</h3>
<h4>{props.cost}</h4>
<img src ={props.image} alt="/"/>
<button onClick={()=>addtoCart(props)}>Add to Cart</button>
</div>
</div>
);
}
export default Products;
It seems you are not passing any props to the ToolBar
Component.
UPDATE: Based on the comments and codesandbox link that you shared indeed this was your problem. No props where being passed to the ToolBar
component.
I have modified the code here on CodeSandBox:
https://codesandbox.io/s/serve-humanity-8hm17
And I would like to point out the fact that If you are passing props to the ToolBar
Component but the Component is rendered before data was available, in that case also you will get this error.
In this case you can add a check:
<span>
Go To Cart:
{cart.length && cart.length}
</span>
Note: To cross-verify whether you are actually receiving any props or not. Do a console.log(props.cart)
in your Toolbar
Component just after declaring it.
function Toolbar(props){
console.log(props);
const {cart} = props;
return(...)
}
This way you will have a better Idea about what is going on with the data and you can better debug your app :)