Skip to main content

Cart Usage

Setup

import { useCart } from 'react-native-stackfront-sdk';
The useCart hook provides the cart state and all mutation methods:
function CartScreen() {
  const {
    cart,              // current cart or null
    loading,           // fetching state
    error,             // last error
    refetch,           // reload cart from API
    addLines,          // add items
    updateLines,       // change quantities
    removeLines,       // remove items
    clearCart,         // start fresh
    getCheckoutUrl,    // get Shopify checkout URL
    updateBuyerIdentity, // set customer on cart
  } = useCart();

  if (loading && !cart) return <Loading />;

  const lines = cart?.lines?.edges ?? [];

  return (
    <View>
      {lines.map(({ node }) => (
        <CartLineItem
          key={node.id}
          item={node}
          onUpdateQty={(qty) => updateLines([{ id: node.id, quantity: qty }])}
          onRemove={() => removeLines([node.id])}
        />
      ))}
    </View>
  );
}

Adding Items

// Add single variant
await addLines([{ merchandiseId: variantId, quantity: 1 }]);

// Add multiple at once
await addLines([
  { merchandiseId: 'gid://shopify/ProductVariant/111', quantity: 2 },
  { merchandiseId: 'gid://shopify/ProductVariant/222', quantity: 1 },
]);
If no cart exists, calling addLines creates one automatically and persists the cart ID.

Updating Quantities

await updateLines([
  { id: 'line-id-1', quantity: 3 },
  { id: 'line-id-2', quantity: 0 }, // zero does NOT remove — use removeLines
]);

Removing Lines

await removeLines(['line-id-1', 'line-id-2']);

Clearing the Cart

await clearCart();
// cart is now null — next addLines creates a fresh cart

Customer Identity

Associate the cart with a logged-in customer:
await updateBuyerIdentity({
  customerAccessToken: 'access-token',
  email: 'customer@example.com',
  countryCode: 'US',
});
This is required for the checkout to recognize the customer and apply their saved addresses and payment methods.

Service API

For imperative use outside React components:
const { cart } = useStackfront();

// Same methods, but no state tracking:
await cart.addLines([...]);
await cart.get();             // returns cart or null
await cart.updateLines([...]);
await cart.removeLines([...]);
await cart.updateBuyerIdentity({...});
await cart.getCheckoutUrl();  // returns URL string
await cart.clear();