How can you develop an add to cart with @bigcommerce/stencil-utils

Step 1 - FormData definition

Firstly you should import the stencil utils;

import utils from "@bigcommerce/stencil-utils";

It should be better define form data object for stencil utils api.

You can use this sample;

let formData = new FormData();
formData.append("action", "add");
formData.append("product_id", 12345);
formData.append("list_price", 10.99);
formData.append("qty[]", 1);

Moreover, you can add variant/option with attribute definition like;

formData.append(`attribute[optionId]`, optionValue);

Step 2 - Handling empty form items from the Form Data object

You can use this function for filtering empty items from Form Data;

filterEmptyFilesFromForm(formData){
    try {
        for (const [key, val] of formData) {
            if (val instanceof File && !val.name && !val.size) {
                formData.delete(key);
            }
        }
    } catch (e) {
        console.error(e); // eslint-disable-line no-console
    }
    return formData;
}

Step 3 - Using itemAdd API for adding cart line items.

After preparing Form Data, you can use this sample for adding to the cart.

utils.api.cart.itemAdd(this.filterEmptyFilesFromForm(formData), (err, response) => {
    const errorMessage = err || response.data.error;
    const cartId = response.data.cart_id;
    const lineItemId = response.data.cart_item.id;
    if (errorMessage) {
        console.log("Error!", errorMessage);
    } else {
        //Get cart quantity and update cart preview.
        utils.api.cart.getCartQuantity({includeOptions: true}, (err, response) => {
            if (err === null) {
                let quantity = response;
                console.log("Product is added to the cart!")

                // Update cart quantity.
                $('body').trigger('cart-quantity-update', quantity);
                $('.cart-quantity')
                    .text(quantity)
                    .toggleClass('countPill--positive', quantity > 0);
            } else {
                console.log("Error!", errorMessage);
            }
        });
    }
});

This adding to cart method avoids getting error while your cart is empty, It defines a cart id if your cart is empty and handling error that prevents might be occured. Moreover, you can use it with React, Angular or Vue JS apps.

That's all, Happy Hacking 🧡