0
Follow
0
View

How to add items to a cart in React

javaprograms 注册会员
2023-01-25 22:36

Edit

I cloned your project, applied my fix and got it to work. The offending code is in App.js, in the handleAddProduct() handler:

const handleAddProduct = product => {
    const ProductExist = cartItems.find(item => item.id === product.id);
    if (ProductExist) {
      setCartItems(
        cartItems.map(item =>
          item.id === product.id
            ? { ...ProductExist, quantity: ProductExist.quantity + 1 }
            : item
        )
      );
    } else {
      setCartItems([...cartItems, { 
        ...product, 
        quantity: ProductExist.quantity + 1  // <-- error is here
      }]);
    }
  };

In the else block, ProductExist is undefined, as the only way to get into the else block is for it to be undefined. But you try to use ProductExist.quantity + 1. It should be just 1, like this:

const handleAddProduct = product => {
    const ProductExist = cartItems.find(item => item.id === product.id);
    if (ProductExist) {
      setCartItems(
        cartItems.map(item =>
          item.id === product.id
            ? { ...ProductExist, quantity: ProductExist.quantity + 1 }
            : item
        )
      );
    } else {
      setCartItems([...cartItems, { 
        ...product, 
        quantity: 1  // <-- Change here
      }]);
    }
  };

With this change, the cart feature is working on my machine, on localhost. There is no UI update to show the new items in the cart, but I checked the console and the items are being added correctly, without errors.

Hope this helped.

Original answer

In components/cts.js, you define the component as:

import productItems from './data/Data'

const Products = ({handleAddProduct, productItems}) => {
  console.log(productItems)
  ...

You override the productItems import by defining it as a prop. This is because of how JavaScript handles scope. The definition in the function parameters takes precedence.

You should change the lines above to remove the prop, like this:

import productItems from './data/Data'

const Products = ({handleAddProduct}) => {
  console.log(productItems)
  ...

You don't pass the productItems prop in App.js, hence the prop is undefined when you try to map over it.

About the Author

Question Info

Publish Time
2023-01-25 22:36
Update Time
2023-01-25 22:36