diff --git a/src/CartSlice.jsx b/src/CartSlice.jsx index 32b8761ed0..96eb4b8fd1 100644 --- a/src/CartSlice.jsx +++ b/src/CartSlice.jsx @@ -7,12 +7,27 @@ export const CartSlice = createSlice({ }, reducers: { addItem: (state, action) => { - + const { name, image, cost } = action.payload; // Destructure product details from the action payload + // Check if the item already exists in the cart by comparing names + const existingItem = state.items.find(item => item.name === name); + if (existingItem) { + // If item already exists in the cart, increase its quantity + existingItem.quantity++; + } else { + // If item does not exist, add it to the cart with quantity 1 + state.items.push({ name, image, cost, quantity: 1 }); + } }, removeItem: (state, action) => { + state.items = state.items.filter(item => item.name !== action.payload); }, updateQuantity: (state, action) => { - + const { name, quantity } = action.payload; // Destructure the product name and new quantity from the action payload + // Find the item in the cart that matches the given name + const itemToUpdate = state.items.find(item => item.name === name); + if (itemToUpdate) { + itemToUpdate.quantity = quantity; // If the item is found, update its quantity to the new value + } }, }, diff --git a/src/ProductList.jsx b/src/ProductList.jsx index 7682c04fc4..11ad45ba25 100644 --- a/src/ProductList.jsx +++ b/src/ProductList.jsx @@ -1,9 +1,12 @@ import React, { useState, useEffect } from 'react'; import './ProductList.css' import CartItem from './CartItem'; +import {addItem} from './CartSlice'; + function ProductList({ onHomeClick }) { const [showCart, setShowCart] = useState(false); const [showPlants, setShowPlants] = useState(false); // State to control the visibility of the About Us page + const [addedToCart, setAddedToCart] = useState({}); const plantsArray = [ { @@ -252,6 +255,15 @@ function ProductList({ onHomeClick }) { e.preventDefault(); setShowCart(false); }; + + const handleAddToCart = (product) => { + dispatch(addItem(product)); // Dispatch the action to add the product to the cart (Redux action) + setAddedToCart((prevState) => ({ // Update the local state to reflect that the product has been added + ...prevState, // Spread the previous state to retain existing entries + [product.name]: true, // Set the current product's name as a key with value 'true' to mark it as added + })); + }; + return (