简体   繁体   中英

Commerce JS add product variant to cart

I'm trying to make a marketplace on my webpage with different types of products. Some are universal, but some have different sizing/type/color or whatnot.

So far I have the product listing and cart functionalities on point, except for the fact that I can't add to cart a products variant.

I've been on the look out on how to do it but there's really not much I could find and I'm not too advanced either. However, I found this in their docs

// If you have udpated your API version and have not yet generated variants
// from your variant groups and options, you\'ll need to update the previous
// `vrnt` object prefix to `vgrp` along with your option id
commerce.cart.add('prod_1ypbroE658n4ea', 1, {
  vgrp_dKvg9l6vl1bB76: 'optn_VPvL5z6O95AQkX'
});

// If you have updated to the latest API version and have variants generated
// from your variant groups and options, all you need to do is send the
// variant id as the third argument in your add to cart method
commerce.cart.add('prod_1ypbroE658n4ea', 1, 'vrnt_dKvg9l6vl1bB76');

and I adjusted to code accordingly: DO notice the commented code in handleAddToCart, when I select that specific product(with that part uncommented, and the other commented) and that specific variant (id based) and add it to cart it works, and adds it to cart with the variant included and it works of course only for that specific product, code & variant - but the uncommented code doesn't work.

    const handleAddToCart = async (productId, quantity,variant ) => {
        // const item = await commerce.cart.add(productId, quantity, {
        //     vgrp_Kvg9l6Lpbo1bB7: 'optn_AYrQlWXv1JwnbR'
        // });
        const item = await commerce.cart.add(productId, quantity, variant);
        setCart(item.cart);
    };

Here is how I manage the product cart functionalty

    const [variant, setVariant] = useState('');

    const handleAddToCart = () => {
        if (product.variant_groups.length >= 1) {
            if (variant === '') {
                setShowPicker(true);
            } else {
                onAddToCart(
                    product.id,
                    1,
                    Object.defineProperty(Object(), product.variant_groups[0].id, {
                        value: variant,
                        writable: false
                    })
                );
            }
        } else {
            onAddToCart(
                product.id,
                1,
                Object.defineProperty(Object(), product.variant_groups[0].id, {
                    value: variant,
                    writable: false
                })
            );
            setShowPicker(false);
        }
    };

                    {showPicker && (
                        <div>
                            <label htmlFor="variant-picker">{product.variant_groups[0].name}</label>
                            <select
                                name="variant-picker"
                                id="variant-picker"
                                value={variant}
                                onChange={(e) => setVariant(e.target.value)}
                            >
                                {product.variant_groups[0].options.map(({ id, name }) => (
                                    <option value={id} key={id}>
                                        {name}
                                    </option>
                                ))}
                            </select>
                        </div>
                    )}

What makes me confuses me the most is that

        Object.defineProperty(Object(), product.variant_groups[0].id, {
            value: variant,
            writable: false
        })

prints exacty as the docs say, or even as the handleAddToCart commented code:

{vgrp_ypbroE4k1w8n4e: 'optn_aZWNoyY0kjo80J'}

But it still won't work, it adds the product to cart, but doesn't register the variant. Can someone point out please what am I doing wrong?

Such an over-engineered approach. I just finished making mine as simple as I could.

Just pass the group Id from a product w variant_groups over 0, this would be product.variant_groups[0].id.

Then you get the option id from product.variant_groups[0].options when you are looping through them to display on a dropdown. The variable would be set in setOptionId(optionId)

once you've set the state for these variables you can call commerce.cart.add(productId, 1, {[groupId]: optionId}) and it will work. I promise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM