javascriptreactjstypeerror

TypeError: Cannot read property 'length' of null in React Project


The code seems to be fine but it's giving this error. It says TypeError: Cannot read property 'length' of null in React Project. I have posted the code below. I am using React Js to build this. Help, please.

import React, {useEffect} from 'react'
import { Link } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { Row, Col, ListGroup, Image, Form, Button, Card } from 'react-bootstrap'
import Message from '../components/Message'
import { addToCart } from '../actions/cartActions'

function CartScreen({ match, location, history }) {
    const productId = match.params.id
    const qty = location.search ? Number(location.search.split('=')[1]) : 1
    
    const dispatch = useDispatch()

    const cart = useSelector(state => state.cart)
    const { cartItems } = cart

    useEffect(() => {
        if (productId){
            dispatch(addToCart(productId, qty))
        }
    }, [dispatch, productId, qty])


    return (
        <Row>
            <Col md={8}>
                <h1>Shopping Cart</h1>
                {cartItems.length === 0 ? (
                    <Message variant='info'>
                        Your cart is empty <Link to='/'>Go Back</Link>
                    </Message>
                ) : (
                        <ListGroup variant='flush'>
                            
                        </ListGroup>
                    )}
            </Col>
        </Row>
    )
}

export default CartScreen 

Solution

  • Like the error say, it's just because your cartItems is null.

    The variable can be null and defined 1 seconde after, but when the variable is null you have this error so you never see the variable with no null value.

    Here are three ways to fix your problem.

    1)

    {cartItems?.length === 0 ? ( // add a ?. to check if variable is null
      <Message variant='info'>
        Your cart is empty <Link to='/'>Go Back</Link>
      </Message>
    ) : (
      <ListGroup variant='flush'>
    
      </ListGroup>
    )}
    
    {cartItems && cartItems.length === 0 ? ( // you check if the var is defined before check the length
      <Message variant='info'>
        Your cart is empty <Link to='/'>Go Back</Link>
      </Message>
    ) : (
      <ListGroup variant='flush'>
    
      </ListGroup>
    )}
    
    function CartScreen({ match, location, history }) {
        // ...
    
        // add a conditional render
        if (!cartItems) return <p>Loading...</p>
    
        return (
            <Row>
                <Col md={8}>
                    <h1>Shopping Cart</h1>
                    {cartItems.length === 0 ? (
                        <Message variant='info'>
                            Your cart is empty <Link to='/'>Go Back</Link>
                        </Message>
                    ) : (
                            <ListGroup variant='flush'>
                                
                            </ListGroup>
                        )}
                </Col>
            </Row>
        )
    }