DEV Community

joshuamwo
joshuamwo

Posted on

I'm sure there is a better way of doing this...

  function increaseItemQuantity(cartItem: Item) {
    setCart((items) => {
      const cartItemExists = items.find((item) => item.id === cartItem.id);

      if (!cartItemExists) {
        const newItem: CartItem = {
          id: cartItem.id,
          quantity: cartItem.quantity,
          variants: [cartItem.variant],
        };

        return [...items, newItem];
      }

      return items.map((item) => {
        if (item.id === cartItem.id) {
          const existingVariant = item.variants.find(
            (variant) => variant.name === cartItem.variant.name
          );

          if (!existingVariant) {
            return {
              ...item,
              quantity: item.quantity + cartItem.quantity,
              variants: [
                ...item.variants,
                { name: cartItem.variant.name, quantity: 1 },
              ],
            };
          }

          return {
            ...item,
            quantity: item.quantity + cartItem.quantity,
            variants: item.variants.map((variant) =>
              variant.name === cartItem.variant.name
                ? {
                    name: variant.name,
                    quantity: variant.quantity + cartItem.quantity,
                  }
                : variant
            ),
          };
        }

        return item;
      });
    });
  }
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
olddutchcap profile image
Onorio Catenacci

Welcome to Dev.to!

Not trying to discourage you or anything like that but I think you may get better assistance if you share your code on a website devoted to peer review. Perhaps this one: codereview.stackexchange.com Or if you have some specific idea about what you think could be improved, perhaps you could tell us and we can offer suggestions to you.

Collapse
 
joshuamwo profile image
joshuamwo

Thanks.