Help and docs
Sign in

demo/acme-web code browser

checkout-redesign cc062bd
TypeScript · 39 lines · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { useState } from "react";
import { charge } from "../api/client";
import { useCart } from "../cart/store";
import { formatMoney } from "../lib/money";
import { CardForm } from "./CardForm";

export function Checkout() {
  const cart = useCart();
  const [status, setStatus] = useState<"idle" | "paying" | "paid" | "failed">("idle");
  const total = cart.total("USD");

  if (status === "paid") return <p>Thanks! Your order is on its way.</p>;
  return (
    <section>
      <h2>Checkout</h2>
      <ul>
        {cart.lines.map((l) => (
          <li key={l.product.id}>
            {l.quantity} × {l.product.name}
          </li>
        ))}
      </ul>
      <CardForm
        payLabel={"Pay " + formatMoney(total)}
        onToken={async (token) => {
          setStatus("paying");
          try {
            await charge(token, total);
            cart.clear();
            setStatus("paid");
          } catch {
            setStatus("failed");
          }
        }}
      />
      {status === "failed" && <p role="alert">The payment did not go through.</p>}
    </section>
  );
}