DEV Community

Cover image for How To Use Shopify Cart API and Add Multiple Products To The Cart
Michael Myers
Michael Myers

Posted on • Edited on

How To Use Shopify Cart API and Add Multiple Products To The Cart

Adding multiple products to the Shopify cart from one button might be helpful in different scenarios, for example when you want to add a configurator.

Recently I said I’m working on a configurator in Shopify without any apps. And here’s an update. I’m attaching the screencast of how it works so far. It’s not 100% done and I found a couple of bugs recently. Anyway, the pre-build version is ready and I’m happy to share it with you.

The issues before starting

The first issue was to properly design it. The design I got from the client was… not in good shape. There was nothing about the different conditions of the products. For example, out-of-stock, discounts, adding products to the cart error, etc. The design didn’t have it and I started to make it myself.

And the second one is to build it. In the process of making it live, if properly say when I started to debug it. I tested the prices, and the main question was “Are the prices shown correctly?”. On the fifth screen, I added the prices of the products that the user chose. In the design, prices aren’t included. I found it helpful to show the prices to the user again.

The working process

Firstly, was made an HTML version. Secondly, I converted it to Liquid code. The problem with HTML is that the products and prices were hard-coded. And with Liquid code all the data is dynamic and customizable through the theme editor which is super cool!

The issue after starting

The main issue was to add multiple products to the cart. I thought about how to make it properly read the documentation (a lot). I read on Shopify discussions, and asked different developers about “how to add multiple products to the cart from one click?” — No luck at all. I tried it on my test Shopify store because thought maybe the problem was in a theme I worked on. But no, the problem was in me :) Later I got an idea and implemented this into the configurator.

The users can add multiple products to the cart now (not sure of the limit of how many products they can add, but 10 it’s 100%).

The solution

To add multiple products to the cart you need to send to the Cart API an items object with the product ID and the quantity.

items object

But be sure to send a variant ID of the product instead of product ID, if your product has variants.

items: [
  {
   id: 36110175633573,
   quantity: 2
  }
]
Enter fullscreen mode Exit fullscreen mode

Here’s how I made a fetch request:

document.querySelectorAll("form.configurator-form").forEach((form) => {
  form.addEventListener("submit", async (e) => {
    e.preventDefault();

    // Show loading spinner
    const loadingOverlays = document.querySelectorAll(".loading-overlay");
    loadingOverlays.forEach((overlay) => overlay.classList.remove("hidden"));

    // Collect product data
    const productData = selectedProducts.map((product) => ({
      id: product.id,
      quantity: 1,
      variantId:
        product.variantId && product.variantId !== product.id
          ? parseInt(product.variantId)
          : undefined,
    }));

    const requestBody = {
      items: productData,
    };

    // Add products to cart
    await fetch(`${window.Shopify.routes.root}cart/add.js`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(requestBody),
    });

    // Get updated cart data
    const res = await fetch("/cart.json");
    const cart = await res.json();

    // Update cart count
    document.querySelectorAll(".cart-count-bubble").forEach((el) => {
      el.textContent = cart.item_count;
    });

    // Navigate to cart page
    window.location.href = "/cart";
  });
});
Enter fullscreen mode Exit fullscreen mode

Overall

I like the project. It will be great for users to get the unique experience and build the box they want. That was a real challenge and I gained a lot of experience from this project.

Be careful when you are faced with this task, there are quite a few pitfalls. For example, if a product has no options, then the ID in value should be passed like this:

{{ product.selected_or_first_available_variant.id }}
Enter fullscreen mode Exit fullscreen mode

The full code of the transmitted input will look like this:

<input class="visually-hidden" type="radio" name="product" value={{ product.selected_or_first_available_variant.id }}>
Enter fullscreen mode Exit fullscreen mode

But if there are options, then this is it: {{ product.id }}

The complete code is similar to the previous input, just the value is different:

<input class="visually-hidden" type="radio" name="product" value={{ product.id }}">
Enter fullscreen mode Exit fullscreen mode

Here's a little trick that you now know. And now you can add multiple items to your cart. Happy development!

Top comments (0)