1

this is the code I am working with. When the cart component is not active the cart data loads perfectly, but when the cart component is active cart data is undefined.

import './App.css';
    import { commerce } from './lib/commerce';
    import { NavBar, Products, Cart } from './components';
    import { useEffect, useState } from 'react';
    
    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);
        fetchCart();
      }
    
      useEffect(() => {
        fetchProducts();
        fetchCart();
      }, [])
      return (
        <div>
          <NavBar totalItems={cart.total_items}></NavBar>
          <Products products={products} handleAddToCart={ handleAddToCart}/>
          <Cart cart={cart}></Cart>
          
        </div>
      );
    }
    
    export default App;
    

NavBar component is receiving the prop. But whenever I pass the cart data into the cart component, data is not being received by Cart component. Even in App.js, the data shows undefined. When Cart component is active

When cart component is not active the top right corner shows cart data

Cart Component

import React from 'react';
    import { Container, Typography, Button, Grid } from '@material- 
     ui/core';
    import useStyles from './styles';
    
    
    const Cart = ({ cart}) => {
      const classes = useStyles();
      // alert(cart);
      const isEmpty = !cart.line_items.length;
      const EmptyCart = () => {
        <Typography variant="subtitle1">You have no items in your shopping 
         cart. Start adding some!</Typography>
      }
      const FilledCart = () => {
        <>
          <Grid container spacing={ 3}>
            {cart.line_items.map((item) => (
              <Grid item xs={12} sm={4} key={item.id}>
                <div>{ item.name}</div>
              </Grid>
              
            ))}
          </Grid>
          <div className={classes.cardDetails}>
            <Typography variant="h4">Subtotal: 
             {cart.subtotal.formatted_with_symbol}</Typography>
            <div>
              <Button className={ classes.emptyButton} size="large" 
               type="button" variant="contained" color="secondary">Empty 
               Cart</Button>
              <Button className={ classes.checkoutButton} size="large" 
               type="button" variant="contained" 
               color="primary">Checkout</Button>
            </div>
            </div>
        </>
      }
      return (
        <Container>
          <div className={ classes.toolbar}>
            <Typography className={classes.title} variant="h3"> Your 
             Shopping 
             Cart</Typography>
            { isEmpty? <EmptyCart /> : <FilledCart />}
          </div>
        </Container>
      );
    };
    
    export default Cart;

Navbar Component

import React from 'react';
    import { AppBar, Toolbar, IconButton, Badge, MenuItem, Menu, 
    Typography } 
    from '@material-ui/core';
    import { ShoppingCart } from '@material-ui/icons';
    import useStyles from './styles';
    import image from '../../images/commerce.png'
    
    const NavBar = ({ totalItems}) => {
        const classes = useStyles();
        return (
            <>
                <AppBar position="fixed" className={ classes.appBar} 
                 color="inherit">
                    <Toolbar>
                        <Typography variant="h6" className={ 
                         classes.title} 
                         color="inherit">
                            <img src={image} alt="My Shop" className= 
                             {classes.image} height="25px" />
                            My Shop
                        </Typography>
                        <div className={classes.grow}></div>
                        <div className={classes.button}>
                            <IconButton aria-label="Show Cart Button" 
                             color="inherit">
                                <Badge badgeContent={totalItems} 
                                 color="secondary">
                                    <ShoppingCart></ShoppingCart>
                                </Badge>
                            </IconButton>
                        </div>
                    </Toolbar>
                </AppBar>
            </>
        );
    };
        
      export default NavBar;
  • Please try to include all relevant code. Update your question to include the `Cart` component. Can you also clarify how `NavBar` has correct cart data but the component holding that state doesn't? – Drew Reese Jun 01 '21 at 05:19
  • Hello there, I have attached screenshots and codes also. Can you please help? – Mohammed Asif Jun 01 '21 at 07:11
  • Error is saying that `cart.line_items` is undefined. This seems to be set by `commerce.cart.add(productId, quantity)`, though, so you should check what this function returns. Can you update your question to include this `commerce` code and drop a `console.log` or `debugger` on the line after `const item = await commerce.cart.add(productId, quantity);` in `handleAddToCart` to see what the value of `item` is that you are updating `cart` state to? – Drew Reese Jun 01 '21 at 07:22
  • When the Cart component in App.js is inactive the console.log(cart) shows cart data. but when I active the Cart component in app.js the console.log is undefined. if I pass cart.total_items in NavBar component, it shows cart items count in NavBar as the pictures described. But when the Cart component is active the cart.total_items has no value. This is like ghost playing to me. – Mohammed Asif Jun 02 '21 at 08:32

0 Answers0