Home > Software design >  Adding the function to remove products from the cart won't allow me to add more products
Adding the function to remove products from the cart won't allow me to add more products

Time:03-07

I have this function to add products and with their colors, however, once I added the functionality to remove products with their colors as well, it does not allow me to add a product anymore.

  1. Add products and along with the selected color
  2. Clicking the "-" button will remove the selected color for that product alone. What happens here is that if I'll add this functionality. it does not allow me to add any products anymore. There's no error that shows in the console nor does the app crashes as well.

How can I fix this? Thank you

Codesandbox: https://codesandbox.io/s/add-to-cart-sampled-2-efqrhd?file=/src/App.js

Codes: App.js

export default function App() {
  const [cartItems, setCartItems] = useState([]);
  const [searchList, setSearchList] = useState([]);
  const [searchKey, setSearchKey] = useState("");

  useEffect(() => {
    let x = [...products];
    x = x.filter((y) => {
      return y.prodName
        .toLocaleLowerCase()
        .includes(searchKey.toLocaleLowerCase());
    });
    setSearchList(x);
  }, [searchKey]);

  const handleAdd = (id, name, price, size, cat, color) => {
    console.log("add", id, name, price, size, cat, color);
    const productExist = cartItems.find(
      (item) => item.id === id && item.color === color
    );

    if (productExist) {
      setCartItems(
        cartItems.map((item) =>
          item.id === id && item.color === color
            ? { ...productExist, quantity: productExist.quantity   1 }
            : item
        )
      );
    } else {
      setCartItems([
        ...cartItems,
        { id, name, price, size, cat, color, quantity: 1 }
      ]);
    }
  };

  const handleRemove = (product) => {
    console.log(product, "remove");
    const ProductExist = cartItems.find(
      (item) => item.id === product.id && item.color === product.color
    );

    if (ProductExist.quantity === 1) {
      setCartItems(cartItems.filter((item) => item.id !== product.id));
    } else {
      setCartItems(
        cartItems.map((item) =>
          item.id === product.id && item.color === product.color
            ? { ...ProductExist, quantity: ProductExist.quantity - 1 }
            : item
        )
      );
    }
  };

  const handleCartClearance = () => {
    setCartItems([]);
  };

  console.log(cartItems);

  return (
    <div className="App">
      <div>
        <input
          placeholder="Search product..."
          value={searchKey}
          onChange={(e) => setSearchKey(e.target.value)}
        />
        {searchList.map((item, index) => (
          <ul key={item.id}>
            <li>
              <b>{item.prodName}</b>
            </li>
            <li>Category: {item.cat}</li>

            <li>Size: {item.size}</li>
            <li>Php {item.price}.00</li>
            {Object.entries(item.colorMap).map((color) => (
              <>
                {color[1] !== 0 ? (
                  <>
                    {color[0]}

                    <button
                      onClick={(e) =>
                        handleAdd(
                          item.id,
                          item.prodName,
                          item.price,
                          item.size,
                          item.cat,
                          color[0]
                        )
                      }
                    >
                      Add
                    </button>
                    {/* <button onClick={(e) => handleAdd(index)}>Add to Cart</button> */}
                  </>
                ) : (
                  <>2</>
                )}
                <br />
              </>
            ))}
          </ul>
        ))}
      </div>
      <Cart
        cartItems={cartItems}
        handleCartClearance={handleCartClearance}
        handleRemove={handleRemove}
        handleAdd={handleAdd}
      />
    </div>
  );
}

Cart.js

const Cart = ({ cartItems, handleCartClearance, handleRemove, handleAdd }) => {
  console.log(cartItems, "items");

  const totalAmount = cartItems.reduce(
    (price, item) => price   item.quantity * item.price,
    0
  );

  return (
    <div>
      Cart page
      {cartItems.length >= 1 && (
        <button onClick={handleCartClearance}>Clear Orders</button>
      )}
      {cartItems.length === 0 && <div>No Items in the cart</div>}
      <div>
        {cartItems.map((item) => (
          <div key={item.id}>
            <li>{item.id}</li>
            <li>{item.name   " "   item.size   ""   item.cat}</li>
            <li>{item.color}</li>
            <li>{item.quantity}</li>

            <li>Total: {parseInt(item.quantity) * parseInt(item.price)}</li>
            <button
              onClick={(e) =>
                handleAdd(
                  item.id,
                  item.prodName,
                  item.price,
                  item.size,
                  item.cat,
                  item.color
                )
              }
            >
               
            </button>
            <button onClick={handleRemove(item)}>- </button>
          </div>
        ))}

        <div>
          <b>Total Amount :{totalAmount}</b>
        </div>
      </div>
    </div>
  );
};

export default Cart;

CodePudding user response:

I think you should go simple to complex. As long as I understand, you have (1) UserInput (i.e. searchKey)
(2) List (i.e. SearchList)
(3) Cart (i.e. cartItems).
You need 2 functions.
(1). addToCart(item)
(2). removeFromCart(item)

function addToCart(item){
//check item already exists or not
//if exists, return
//if not addToCart
}
function removeFromCart(item){
//check item exists in cart
//if not, return
//if exists, removeFromCart
}

You have arrays of objects. It is easy to check item exists or not with filter().

const List = [{id: 0, name: 'a'},{id: 1, name: 'b'},...];
function addToCart(item){
const alreadyExist = List.filter(listItem=> listItem.id === item.id).length > 0;
if (alreadyExist) return;
//else execute the rest of the function
//I used spread iterator
setCartItems([...cartItems, item]);
}
function removeFromCart(item){
//these codes not even necessary
//const alreadyExist = cartItems.filter(cartItem=> cartItem.id === item.id).length > 0;
//if (!alreadyExist) return;
setCartITems(cartItems.filter(cartItem=> cartItem.id !== item.id);
}

what I am saying is, build simple functions first, then go to complex. Then, you will know where the error occurs. There is a way to debug when error does not show on screen. console.log(). It can show you the value of your variables during the function. for example,

function addToCart(item){
console.log('Before adding CartItems is ', cartItems);
const alreadyExist = List.filter(listItem=> listItem.id === item.id).length > 0;
console.log('CartItem already Exist?', alreadyExist);
if (alreadyExist) return;
//else execute the rest of the function
//I used spread iterator
setCartItems([...cartItems, item]);
console.log(item, ' new item was added to CartItems');
}
  • Related