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
Inside App component instead of setcart(item.cart)
correct it to setcart(item)
const handleaddtocart = async(productId,quantity) => {
const item = await commerce.cart.add(productId,quantity)
setcart(item)
}