React
@shoppable/checkout-react puts one checkout client and one server-priced cart in your React
tree. It builds on @shoppable/checkout and works with React 17 and later.
npm install https://developer.shoppable.com/sdk/shoppable-checkout-0.2.1.tgz \ https://developer.shoppable.com/sdk/shoppable-checkout-react-0.1.1.tgzExample
A product button and a cart summary that re-prices on every change:
import { cheapestOffer } from "@shoppable/checkout";import { CartProvider, ShoppableProvider, useCart, useProducts, useShoppable,} from "@shoppable/checkout-react";
export function App() { return ( <ShoppableProvider token="pk_test_..."> <CartProvider> <AddToCart upc="00012345678905" /> <CartSummary /> </CartProvider> </ShoppableProvider> );}
function AddToCart({ upc }: { upc: string }) { const { products, loading, error } = useProducts([upc]); const { addItem } = useCart(); if (loading) return <p>Loading...</p>; if (error) return <p>{error.message}</p>;
const product = products[0]; const offer = product && cheapestOffer(product); if (!offer) return <p>Not available.</p>;
return ( <button onClick={() => addItem({ upc: product.upc, merchantId: offer.merchantId, quantity: 1 })}> Add {product.name} from {offer.name} </button> );}
function CartSummary() { const { config, error: configError } = useShoppable(); const { items, checkout, pricing, error, setQuantity, removeItem, applyCoupon } = useCart(); if (configError) return <p>{configError.message}</p>; if (!config) return <p>Loading…</p>; if (items.length === 0) return <p>Your cart is empty.</p>; if (!checkout) return error ? <p role="alert">{error.message}</p> : <p>Pricing your cart…</p>;
const money = new Intl.NumberFormat(config.language, { style: "currency", currency: config.currency });
return ( <section aria-busy={pricing}> {config.isTestMode && <span>Test mode</span>} {error && <p role="alert">{error.message}</p>}
{checkout.merchants.map((merchant) => ( <div key={merchant.merchantId}> <h3>From {merchant.name}</h3> {merchant.products.map((line) => ( <div key={line.id}> {line.name} {money.format(line.salePrice)} <input type="number" min={1} max={99} value={line.quantity} onChange={(e) => { // Ignore the empty box while the shopper types; Remove deletes the line. const quantity = e.target.valueAsNumber; if (Number.isInteger(quantity) && quantity >= 1) setQuantity(line.upc, merchant.merchantId, quantity); }} /> <button onClick={() => removeItem(line.upc, merchant.merchantId)}>Remove</button> </div> ))} </div> ))}
<form onSubmit={async (e) => { e.preventDefault(); const code = new FormData(e.currentTarget).get("code") as string; if (!(await applyCoupon(code))) alert("That code isn't valid for this order."); }} > <input name="code" placeholder="Coupon code" /> <button>Apply</button> </form>
<p>Subtotal {money.format(checkout.subTotal)}</p> <p>Shipping {money.format(checkout.shippingTotal)}</p> <p>Discounts {money.format(checkout.discountTotal)}</p> <p>Estimated tax {money.format(checkout.estimatedTax)}</p> <p>Total {money.format(checkout.total)}</p> </section> );}For the payment step, see Payments and pick the React tab.
ShoppableProvider
Creates the client and loads the cart configuration, which also starts the session every checkout call needs. Put it near the root of your app.
<ShoppableProvider token="pk_test_..."> {children}</ShoppableProvider>It accepts every client option as a prop. The client is
recreated only when token, baseUrl or origin change. To share a client you created
yourself, pass it as client instead.
useShoppable
const { client, config, loading, error } = useShoppable();| Field | Description |
|---|---|
client | The ShoppableCheckout instance, for calls the hooks do not cover (for example validateAddress). |
config | The cart configuration once loaded: currency, country, language, stripePublishableKey, isTestMode, branding, and your Cart Builder checkout settings: showMarketingOptIn, marketingOptInCopyText (HTML), checkoutTermsAndPrivacyCopyText (HTML) and allowSubstitution. |
loading | True until the configuration has loaded or failed. |
error | Set when the configuration could not load. A 403 here means your site is not allowed for this token; see Get your keys. |
useProducts
const { products, loading, error } = useProducts(["00012345678905", "00098765432109"]);Looks up products and their retailer offers by UPC (Universal Product Code), and looks them up
again when the list changes. products is a ProductAvailability[]; see
Products and retailer offers.
CartProvider and useCart
CartProvider holds one cart for everything inside it. Place it inside ShoppableProvider.
<CartProvider storageKey="shoppable-cart">{children}</CartProvider>The cart is saved in localStorage under storageKey (default shoppable-cart), so it
survives page loads. Pass storageKey={false} to keep it in memory only.
Every change to items or coupons re-prices the same checkout on the server, as described in Re-pricing as the cart changes.
const cart = useCart();| Field | Description |
|---|---|
items | What the shopper chose: { upc, merchantId, quantity }[]. Quantities live here; prices live on checkout. |
couponCodes | Codes the shopper applied. checkout.coupons shows which still apply. |
checkout | The latest PricedCheckout, or null while the cart is empty or before the first price arrives. Render totals from here. |
pricing | True while the server is re-pricing, including while applyCoupon runs. |
error | The last pricing error, such as “Trail Jacket gone out of stock”. Cleared by the next successful price. A ShoppableValidationError lists the failing lines in body.errors (details). |
addItem(item) | Adds a line, or adds to the quantity of the same product from the same retailer (up to 99). |
setQuantity(upc, merchantId, quantity) | Sets a line’s quantity, capped at 99. Below 1 removes the line. |
removeItem(upc, merchantId) | Removes a line. |
clear() | Empties the cart and forgets the checkout. |
applyCoupon(code) | Prices the cart with the code and resolves true if the server applied it, false if not. |
removeCoupon(code) | Removes a code and re-prices. |
update(patch) | updateCheckout for the current checkout (email, opt-ins). Resolves with the re-priced checkout. |
placeOrder({ confirmPayment, paymentMethod? }) | Places the order for the current checkout (see Payments) and clears the cart on success. |
lastOrder | The CompletedCheckout ({ status, orderNumber }) from the most recent placeOrder, or undefined. Lets a confirmation page tell “just ordered” from “empty cart”. |
When re-pricing fails, error is set and checkout keeps the last successful price, which no
longer matches items. Show error next to the totals. Until the cart prices successfully
again, update and placeOrder reject instead of using the stale checkout, so a shopper can
never pay for a cart they no longer see.
applyCoupon rejects, rather than resolving false, when pricing itself fails (for example an
item went out of stock); handle it like error. Manage coupons with applyCoupon and
removeCoupon rather than update({ coupons }): the cart sends its own coupon list on every
re-price.