Home > front end >  Add Individual Product Clicked to Cart. React Context
Add Individual Product Clicked to Cart. React Context

Time:02-26

I created a cart Array in my Context

 const [cart, setCart] = useState([]);

I want to implement an addToCart Button, on Each Button Click, Add the clicked product to cart, and change the button from Add to cart to Remove from cart on that particular Product, not all products.

const addProduct = (product) => {
    setCart([
      ...cart,
      {
        id: product.id,
        drinkName: product.drinkName,
        price: product.price,
        url: product.url,
      },
    ]);   

};

Shop Page

const { products, storeQuery, addProduct } = useProduct();
// Products are coming from Firebase

  const addToCart = (product) => {
    const newProduct = {
      id: product.id,
      drinkName: product.drinkName,
      price: product.price,
      url: product.url,
    };
    product = newProduct;
    console.log("cart Added");
    addProduct(newProduct);
    console.log(newProduct.id, "Clicked");
  };

<SimpleGrid
              columns={{ base: 2, md: 4 }}
              spacing={{ base: 3, md: 4 }}
            >
              {products?.map((docsSnapshot) => {
                const product = docsSnapshot.data();
                return (
                  <ProductList
                    key={docsSnapshot.id}
                    docsSnapshot={docsSnapshot}
                    product={product}
                    addProductToCart={(product) => addToCart(product)}
                  />
                );
              })}
            </SimpleGrid>

ProductList page

<Button
              isFullWidth
              onClick={() => addProductToCart(product, docsSnapshot?.id)}
              colorScheme="success"
              size={"xs"}
            >
              Add to cart
            </Button>

id: undefined, Why is that happening?

enter image description here

CodePudding user response:

I don't guarantee that each product document has an id field from Firestore.

Refactor code as :


{products?.map((docsSnapshot) => {
                const doc = docsSnapshot.data();
                const product = {...doc,id:docsSnapshot.id}
                return (
                  <ProductList
                    key={docsSnapshot.id}
                    docsSnapshot={docsSnapshot}
                    product={product}
                    addProductToCart={(product) => addToCart(product)}
                  />
                );
              })}


To change Add to cart to Remove to cart label try.


products?.map((docsSnapshot) => {
  const doc = docsSnapshot.data();
  const product = { ...doc, id: docsSnapshot.id };
  // Find product either added to cart.
  const inCart = Boolean(cart.find((el) => el.id === product.id));
  return (
    <ProductList
      key={docsSnapshot.id}
      docsSnapshot={docsSnapshot}
      product={product}
      addProductToCart={(product) => addToCart(product)}
      // Add extra props for to indicate if product added to cart
      isInCart={inCart}
    />
  );
});


Later inside Product page, refactor as below:

<Button
  isFullWidth
  onClick={() => addProductToCart(product, docsSnapshot?.id)}
  colorScheme="success"
  size={"xs"}
>
  {props.isInCart ? "Remove" : "Add"} to cart
</Button>;


CodePudding user response:

Calculate cart total.


const total = cart.map(product=>product.price).reduce(previousValue, currentValue) => previousValue   currentValue,
  0)

console.log({total})

  • Related