Dev.to WebDev ๐Ÿ›  Dev ๐Ÿ‘ 0 ๐Ÿ“– 1 min read

Shopify grocery product cards with unit pricing and Ajax Cart

A grocery product card has two jobs: display comparable prices and send the correct variant and quantity to the cart. Freshmart provides a visual reference for the card and the shopping aisle. Render the unit p

A grocery product card has two jobs: display comparable prices and send the correct variant and quantity to the cart. Freshmart provides a visual reference for the card and the shopping aisle.

Render the unit price for the selected variant

{%- assign variant = product.selected_or_first_available_variant -%}
{%- if variant.unit_price_measurement -%}
  <span class="fm-unit-price">
    {{ variant.unit_price | unit_price_with_measurement: variant.unit_price_measurement }}
  </span>
{%- endif -%}

Configure total measurement and base measurement on the product or variant. Use the same comparison unit within a category. On a pack-size change, update both the label and the selected variant ID.

Handle the cart response before continuing

async function addSelection(items) {
  const root = window.Shopify.routes.root;
  let message = '';

  try {
    const response = await fetch(root + 'cart/add.js', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ items })
    });
    if (!response.ok) {
      const error = await response.json().catch(() => null);
      message = error?.description || 'ๆœ‰ๅ•†ๅ“ๆœชๆŒ‰ๆ‰€้€‰ๆ•ฐ้‡ๅŠ ๅ…ฅใ€‚';
    }
  } catch {
    message = 'ๆœชๆ”ถๅˆฐๅŠ ่ดญ็กฎ่ฎค๏ผŒ่ฏทๆŸฅ็œ‹ๅฝ“ๅ‰่ดญ็‰ฉ่ฝฆใ€‚';
  }

  const currentCart = await fetch(root + 'cart.js');
  if (!currentCart.ok) throw new Error('ๆš‚ๆ—ถๆ— ๆณ•่ฏปๅ–่ดญ็‰ฉ่ฝฆ');
  return { cart: await currentCart.json(), message };
}

Disable the submit button while adding the selection. The Cart API can add the available quantity when the requested quantity exceeds stock. Reconcile the result against the latest cart and show it to the shopper before another attempt.

Test the cases that change the outcome

  • Add across two categories and switch pack sizes.
  • Test a variant already in the cart, a partial-stock response and a network interruption.
  • Confirm the actual discounts, currency and shipping conditions at checkout.

References: Shopify unit price filter, Ajax Cart API and Orbix Studio's Freshmart project.

๐Ÿ“ฐ Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.