How can I save the product variation that was selected

I have these products with product variations of colors. The problem is that it does not record the product’s color that I have added.
For example, the shirt has 2 colors red and green, and I’ll choose red, only the red will be saved and the quantity will be updated for that product as a whole but not on the color.

This is what happens:
ezgif.com-gif-maker

Codesandbox: Add to Cart - CodeSandbox

Codes:

export default function App() {
  const [cartItems, setCartItems] = useState([]);

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

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

  // const handleAdd = (item) => {
  //   console.log("add", item);
  // };

  console.log(cartItems);

  return (
    <div className="App">
      {products.map((index) => (
        <ul key={index.id}>
          <li>
            <b>{index.prodName}</b>
          </li>
          <li>Category: {index.cat}</li>
          <li>Size: {index.size}</li>
          {Object.entries(index.colorMap).map((color) => (
            <>
              {color[1] !== 0 ? (
                <>
                  {color[0]}
                  <button
                    onClick={(e) =>
                      handleAdd(
                        index.id,
                        index.prodName,
                        index.size,
                        index.cat,
                        color[0]
                      )
                    }
                  >
                    Add to Cart
                  </button>
                  {/* <button onClick={(e) => handleAdd(index)}>Add to Cart</button> */}
                </>
              ) : (
                <>2</>
              )}
              <br />
            </>
          ))}
          Php {index.price}.00
        </ul>
      ))}
      <Cart cartItems={cartItems} />
    </div>
  );
}

Try to set quantity property of your cartItems to an object containing the product quantity for each color.

setCartItems([...cartItems, { id, name, size, cat, color, quantity: { Black: 1, Blue: 3 } }]);

Then refactor the logic to increment the quantity of a product.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.