0

I am trying to remove the specific product a user is clicking on.

So far, when you are trying to remove a product from the cart it removes based on the ID the product has. Though, I need it to check size, color, and ID. I don't want it to remove both "Product A, size M" and "Product A, size L" if the user is only clicking on size M.

So for example: enter image description here

If I try to remove the "size M" one, it should only remove the "size M" one, not the "size L" as well (as both of them have the same ID).

Here is my code where the deletion of a product is:

const removeItemHandler = (e) => {
    let id = e.currentTarget.getAttribute("itemid");
    let size = e.currentTarget.getAttribute("size");
    let color = e.currentTarget.getAttribute("color");

    const clonedCartItems = JSON.parse(JSON.stringify(cartItems));

    // Here is where I am trying to filter out the product. So it will only take the one the user is 
    clicking on
    let newCart = clonedCartItems.filter(
      (elem) => elem.id !== id && elem.size !== size
    );

    setCartItems(newCart);
  };

Thanks!

simon sjöö
  • 365
  • 2
  • 3
  • 17

2 Answers2

1

If using React JS, then question like this has already been asked, trick is to pass the index, while calling removeItemHandler

Removing element from array in component state

e.currentTarget.getAttribute("itemid"); this code is dependent on the data, Today your logic dependent on size and color, tomorrow it might be something else

Scalable code : You can assign the UUID (probably v4) while adding the stuffs to the cart and then setting it over attribute (or passing over callback with above approach), then taking the id and finding it.

let id = e.currentTarget.getAttribute("UUID");

with one line this can be generic.

sample code

codesandbox.io/s/delete-items-from-cart-g9qm5?file=/src/App.js

Harsh Mehta
  • 141
  • 5
  • Not really following along, UUID, in this case, is what? Or do you mean that I could set the id, size and color in "one line" then compare it? So it would look something like `idMblack`? – simon sjöö May 30 '21 at 13:01
  • the function which is responsible for adding stuffs to cart, should add one more property, call it as UUID or something, while rendering the delete button, passback the uuid : `removeItemHandler(e,uuid)`, then your logic will be based on a single Id's not based on the data it holds – Harsh Mehta May 30 '21 at 13:04
  • https://codesandbox.io/s/delete-items-from-cart-g9qm5?file=/src/App.js use this link, i have written a sample code – Harsh Mehta May 30 '21 at 13:13
0
let newCart = clonedCartItems.filter(
      (elem) => {
         if(elem.id == id) {
            return elem.size !== size;
         }else
         return elem.id !== id
       }
);