im newbie to react. i developing a portfoliio project guided by youtube video. when i try update state in cart icon which is present in the navbar, the page becomes blank
function App() {
const [products,setproducts] = useState([]);
const [cart,setcart] = useState([])
const fetchproducts = async ()=>{
const {data} = await commerce.products.list();
setproducts(data)
}
const fetchcart = async () => {
setcart(await commerce.cart.retrieve())
}
const handleaddtocart = async(productId,quantity) => {
const item = await commerce.cart.add(productId,quantity)
setcart(item.cart)
}
useEffect(()=>{
fetchproducts();
fetchcart();
},[])
return (
<div className="App">
<Products products={products} Onaddtocart = {handleaddtocart}/>
<Navbar totalitem={cart.total_items} />
</div>
);
}
export default App;
here is my navbar.js which imports total_value as a prop and tends to set a value for badge icon
export const Navbar = ({totalitem}) => {
const classes = useStyles()
return (
<>
<AppBar position='fixed' className={classes.appBar} color="inherit">
<Toolbar>
<Typography variant="h6" color="inherit" className={classes.title}>
<img src={logo} alt="zencart" height="25px" className={classes.image}></img>
ZenMart
</Typography>
<div className='classes.grow'></div>
<div className='classes.button'></div>
<IconButton aria-label="show cart item" color="inherit">
<Badge badgeContent={totalitem} color="secondary">
<ShoppingCart />
</Badge>
</IconButton>
</Toolbar >
</AppBar>
</>
)
}
i need to display the state change in cart icon badge whenever i click on the add to cart button
2
Answers
Inside App component instead of
setcart(item.cart)
correct it tosetcart(item)
The error seems to be that when you pass
totalitem
as a prop to theNavbar
component it’s undefined.To solve this you can verify first that cart is not undefined and then access to the property of
total_items
, for example by adding a optional chaining(?.)
operator: