reactjsrenderingdisplayobject

Cannot display items by pasing value from context component


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/cart/CartList.js


Solution

  • https://codesandbox.io/s/cart-code-addict-forked-uonqs?file=/src/cart/CartList.js

    There are lot of bugs. Context should be imported. Value.length was undefined. Please check the code again and see if data is flowing (Console.log everything to see if everything is as expected). Like props are getting the data. I have fixed cart item problem in the forked sandbox. Please check .