0

So i wanna display my cart item in the cart list, as i have set the initial state of cart to storeProducts, 8 of my products should be rendered as i'm using the map function. I haven't made the ui of my cartItem.js yet, but instead, i should have 8 lines of text as "this is a cart item" from my cartItem.js. Please help me to find out what's wrong with my codes! Thank you so much!

context.js:

class ProductProvider extends React.Component {
  state = {
    products: storeProducts,
    detailProduct: detailProduct,
    cart: storeProducts,
    modalOpen: false,
    modalProduct: detailProduct
  };

  getItem = (id) => {
    const product = this.state.products.find((item) => item.id === id);
    return product;
  };

  addToCart = (id) => {
    let tempProducts = [...this.state.products];
    const index = tempProducts.indexOf(this.getItem(id));
    const product = tempProducts[index];
    product.inCart = true;
    product.count = 1;
    const price = product.price;
    product.total = price;

    this.setState(() => {
      return (
        { products: tempProducts, cart: [...this.state.cart, product] },
        () => console.log(this.state)
      );
    });
  };

  openModal = (id) => {
    const product = this.getItem(id);
    this.setState(() => {
      return { modalProduct: product, openModal: true };
    });
  };

  closeModal = (id) => {
    this.setState(() => {
      return { modalOpen: false };
    });
  };

  render() {
    return (
      <ProductContext.Provider
        value={{
          ...this.state,
          addToCart: this.addToCart,
          openModal: this.openModal,
          closeModal: this.closeModal
        }}
      >
        {this.props.children}
      </ProductContext.Provider>
    );
  }
}

CartItem.js:

import React from "react";

function CartItem(item) {
  return <div>this is a cart item</div>;
}

export default CartItem;

CartList.js:

import React from "react";
import CartItem from "./CartItem"

export default function CartList (props) {
   const {cart} = props
    return (
      <div>
        {cart.map((item) => (
            <CartItem key={item.id} item={item} />
        ))}
      </div>
    )
}

Sandbox link:https://codesandbox.io/s/cart-code-addict-buz0u?file=/src/App.js

na ha
  • 175
  • 1
  • 8

1 Answers1

0

In your Sandbox link, EmptyCart component can not found, so the app is error.

And your should add ProductConsumer too.

'PropTypes' is defined but never used. (no-unused-vars)
eslint
'useParams' is defined but never used. (no-unused-vars)
eslint
'Modal' is defined but never used. (no-unused-vars)
eslint
Missing radix parameter. (radix)
eslint
'ProductConsumer' is not defined. (react/jsx-no-undef)
eslint
Michael An
  • 181
  • 9