# Add to cart and a mini cart

An add-to-cart button for your product pages and a bag in the header that shows the server's Lines and total.

You build a button that puts the green trail backpack in the bag, and a header bag that counts the
units and opens to show each Line and the estimated total. It survives reloads and starts afresh
after a purchase.

**You need** a React Router storefront and Nordgrat running from the [Quickstart](/getting-started).
Copy `ORBCART_URL` and `ORBCART_PUBLISHABLE_KEY` from the file [`orbcart dev`](/sdks/cli) wrote into
your storefront's `.env` as `VITE_ORBCART_URL` and `VITE_ORBCART_PUBLISHABLE_KEY`. The publishable
key is safe in the browser.

## 1. Connect once

```ts title="app/commerce.ts"
import { createCommerce } from "@orbcart/client";

export const commerce = createCommerce({
  url: import.meta.env.VITE_ORBCART_URL,
  key: import.meta.env.VITE_ORBCART_PUBLISHABLE_KEY,
});
```

## 2. Keep the Cart token in a cookie

The token opens the Cart and the buyer's details, so only your server keeps it, in an HttpOnly cookie
([Security](/security#keys-and-tokens)). Add `app/cart-cookie.server.ts` and the `/cart-token` route
from [Keep the Cart across reloads](/commerce#in-a-cookie).

## 3. Hold the Cart on every page

`CartProvider` opens the buyer's Cart from the cookie, creates the first one with the first Line and
moves to the next one after a purchase. `onCartChange` says when to save a new token:

```tsx title="app/root.tsx (trimmed)"
import type { CommerceCart } from "@orbcart/client";
import { CartProvider, OrbCartProvider } from "@orbcart/react";
import "@orbcart/react/styles.css";
import { Outlet, useLoaderData } from "react-router";
import type { LoaderFunctionArgs } from "react-router";
import { cartCookie } from "./cart-cookie.server";
import { commerce } from "./commerce";
import { MiniCart } from "./mini-cart";

export async function loader({ request }: LoaderFunctionArgs) {
  const token: unknown = await cartCookie.parse(request.headers.get("Cookie"));
  return { cartToken: typeof token === "string" ? token : undefined };
}

export default function App() {
  const { cartToken } = useLoaderData<typeof loader>();

  return (
    <OrbCartProvider locale="en-GB">
      <CartProvider
        commerce={commerce}
        {...(cartToken !== undefined && { token: cartToken })}
        onCartChange={rememberCart}
      >
        <header>
          <a href="/">Nordgrat</a>
          <MiniCart />
        </header>
        <Outlet />
      </CartProvider>
    </OrbCartProvider>
  );
}

function rememberCart(cart: CommerceCart) {
  void fetch("/cart-token", { method: "POST", body: new URLSearchParams({ token: cart.token }) });
}
```

## 4. The button

```tsx title="app/add-to-bag.tsx"
import { CommerceError, describe } from "@orbcart/client";
import { useShoppingCart } from "@orbcart/react";
import { useState } from "react";

const words = describe("en-GB");

export function AddToBag({ reference }: { reference: string }) {
  const { add } = useShoppingCart();
  const [adding, setAdding] = useState(false);
  const [problem, setProblem] = useState<string>();

  async function addToBag() {
    setAdding(true);
    setProblem(undefined);
    try {
      await add(reference);
    } catch (error) {
      if (!(error instanceof CommerceError)) throw error;
      setProblem(words.problem(error.problem.code));
    } finally {
      setAdding(false);
    }
  }

  return (
    <>
      <button type="button" onClick={addToBag} disabled={adding}>
        Add to bag
      </button>
      {problem && <p role="alert">{problem}</p>}
    </>
  );
}
```

Put `<AddToBag reference="BACKPACK-30-GREEN" />` on the product page. The browser sends only the
reference; the price comes from your [`offers`](/integrations) function.

## 5. The mini cart

```tsx title="app/mini-cart.tsx"
import { isSubmitted, unitsIn } from "@orbcart/client";
import type { CommerceCart } from "@orbcart/client";
import { Cart, Totals, useCart, useShoppingCart } from "@orbcart/react";

export function MiniCart() {
  const { cart } = useShoppingCart();

  // There is no Cart before the first Line, so an empty bag costs no request.
  return cart ? <Bag key={cart.id} cart={cart} /> : <a href="/cart">Bag (0)</a>;
}

function Bag({ cart }: { cart: CommerceCart }) {
  const bag = useCart({ cart });
  if (!bag.cart) return <a href="/cart">Bag</a>;
  // An ordered Cart stays until the buyer shops on; the next add starts a fresh one.
  if (isSubmitted(bag.cart)) return <a href="/cart">Bag (0)</a>;
  const { estimate } = bag.cart;

  return (
    <details className="mini-cart">
      <summary>Bag ({unitsIn(bag.cart)})</summary>
      <Cart
        cart={bag.cart}
        pending={bag.pending}
        onQuantityChange={bag.setQuantity}
        onRemove={bag.remove}
      />
      <Totals
        compact
        totals={estimate.totals}
        discounts={estimate.discounts}
        pricesIncludeTax={estimate.pricesIncludeTax}
        shipping={estimate.shipping}
        excludes={estimate.excludes}
      />
      <a href="/checkout">Check out</a>
    </details>
  );
}
```

`useCart` and the button share one queue per Cart, so the count changes when the server has
answered, never before.

## What the buyer sees

* **Add to bag** turns the header into "Bag (1)". Open it for the backpack at €89.90, a quantity
  stepper and the total, marked as without shipping until a method is chosen.
* **More than is in stock** is said under its Line, and the quantity stays what the server allows.
* **A reference your `offers` does not sell** shows as unavailable, with the reason.
* **A reload or a second tab** shows the same bag. **After the purchase** the bag is empty, and the
  next add starts a new Cart in every tab.

## Next

* [React checkout](/sdks/react): the `/checkout` page this bag links to, in one component.
* [Carts](/commerce): the same steps with the plain client, for other frameworks.
* [Free shipping and a welcome code](/recipes/free-shipping-and-codes): add a code field to this bag.