TypeError: Cannot read property 'map' of undefined, cart

283 Views Asked by At

I have 2 components App.js and Cart.js I'm using material-ui and commerce.js api for this application App.js:

import React , {useState , useEffect} from 'react'
import Products from './Components/Products/Products'
import Navbar from './Components/NavBar/Navbar'
import {commerce} from './assests/lib/Commerce'
import Cart from './Components/Cart/Cart'

export default function App(props) {

    const [products , setproducts] = useState([])
    const [cart , setCart] = useState([])

    const fetchData = 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(()=>{
        fetchData()
        fetchCart()
    },[])

    console.log(products)
    console.log(cart)
    return (
                   <>
           
           < Navbar totalItems={cart.total_items}/>
           <Cart cart={cart}/>
           </>
    )
}

Cart.js:

import React from 'react'
import {Container ,  Grid , Button , Typography} from '@material-ui/core'
import useStyles from './styles'
//import cart from '../../App'

const Cart = ({cart}) => {


    console.log(cart)


    
    const classes = useStyles();



    const isEmpty = cart.length

    const EmptyCart = ()=>{
        <Typography variant='2' >Your Cart is Empty</Typography>
    }
    const FilledCart = (cart) =>{
        <>
        <Grid Container spacing={3} >
            {cart.line_items.map((cartitem)=>
            (
                <Grid item xs={12} sm={4} key={cartitem.id}>
                    {cartitem.name}

                </Grid>
            ))}
            </Grid>
            <div className={classes.cardDetails}>
                <Typography variant='h4'>
                    SubTotal : {Cart.subtotal.formated_with_symbol}

                </Typography>
            </div>
            <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'>
                    Check out Cart
                </Button>
            </div>
            </>
    }
    return (
       <Container>
           <div className={classes.toolbar}/>
           <Typography variant="3" className={classes.title}>
               Your Shopping Cart
           </Typography>
           { isEmpty ? <EmptyCart /> : <FilledCart /> }
       </Container>
    )
}

export default Cart

When I try to run it it says "can't read property of undefined , cart"

1

There are 1 best solutions below

2
Shyam On

When you are rendering for the first time your cart.length is 0 . So isEmpty will have the value 0 which is a falsy value . So your FilledCart will get rendered instead of EmptyCart.

Since its an empty array cart.lineitems will be undefined . Here the error cannot do map on undefined .

So you need to change your code as

const isEmpty = cart.length === 0