Skip to main content

Add to cart

The add to cart functions check whether the customer can add the selected variant to the cart and find the cart line that already holds a variant. Use these functions to enable the add-to-cart button and show the quantity that's already in the cart.

Import canAddToCart and findCartLineByMerchandiseId from @shopify/hydrogen.


Checks whether the customer can add the current selection to the cart. Use the result to enable or disable the add-to-cart button.

Anchor to product
product
TProduct extends <>
required

The product from your query. A product that requires a selling plan always returns false.

Anchor to options
options
<<TProduct>, <TProduct>>[]
required

The options array from the product form state.

false | true

true when the selection resolves to a variant that's available for sale and the product doesn't require a selling plan.

Examples

TypeScript

import { canAddToCart, type ProductFormStore, type ProductInput } from "@shopify/hydrogen";

declare const product: ProductInput;
declare const store: ProductFormStore;
declare const button: HTMLButtonElement;

function render(state: ReturnType<typeof store.getState>) {
const addable = canAddToCart(product, state.options);

button.disabled = !addable;
if (addable) {
button.textContent = "Add to cart";
} else if (product.requiresSellingPlan) {
button.textContent = "Choose a subscription";
} else if (state.selectedVariant) {
button.textContent = "Sold out";
} else {
button.textContent = "Select options";
}
}

render(store.getState());
store.subscribe(render);

Finds the cart line that holds a variant. Use the line to show the quantity that's already in the cart.

When several cart lines hold the variant with different selling plans or attributes, the function returns the first line.

Anchor to lines
lines
[]
required

The cart lines, such as data.lines.nodes from the cart state.

Anchor to merchandiseId
merchandiseId
string
required

The variant ID to look for.

| null

The first cart line that holds the variant, or null when no cart line holds the variant.

Examples

TypeScript

import { findCartLineByMerchandiseId, type CartStore } from "@shopify/hydrogen";

declare const cartStore: CartStore;
declare const variantId: string;

const line = findCartLineByMerchandiseId(cartStore.getState().data.lines.nodes, variantId);

if (line) {
console.log(`Already in cart, quantity ${line.quantity}`);
}

Was this page helpful?