Skip to content

Unhandled Rejection (TypeError): Cannot read properties of null (reading ‘product’)

This error appears to me when I add something to the shopping cart . I’ve checked the code many times, but I still can’t find the solution, I don’t know how to make it work.

code in cartActions.js

import axios from 'axios' 
import { CART_ADD_ITEM } from '../constants/cartConstants';

export const addToCart = (id, qty) => async (dispatch, getState) => {
    const { data } = await axios.get(`/api/products/${id}`)

        type: CART_ADD_ITEM,
        payload: {
            product: data._id, 
            image: data.image,
            price: data.price,
            countInStock: data.countInStock, 


    localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))

code in cardReducers.js I think the problem comes from here, but I don’t know exactly where to change

import {  CART_ADD_ITEM  } from "../constants/cartConstants"

export const cartReducer = (state = { cartItems: [] }, action) => {
    switch (action.type) {
        case CART_ADD_ITEM:
            const item = action.payload
            const existItem = state.cartItems.find(x => x.product === item.product)

                    cartItems: =>
                        x.product === existItem.product ? item:x)

                    cartItems:[...state.cartItems, item]
            return state;



code in CartScreen.js

import React, {useEffect} from 'react'
import { useParams, useLocation } 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() {
  const {prodId} = useParams()
  const location = useLocation()
  const qty = ? Number('=')[1]) : 1
  const dispatch = useDispatch()

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

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



export default CartScreen  

Here I have attached an image with the error

enter image description here



Why did you remove the else statement? Of course it won’t work if you omit this logic 😀

The code inside the store.js seems fine. Please clear your local storage and try again. If you don’t know how to do that, delete your browser data or follow the guide here.

9 People found this is helpful