AI Hints
Home›React Tutorial›Project: Checkout
React · Lesson 105 of 120

Project: Placing the Order

Async submit.

⏱ 2 min read▶ Video at 1:27:35🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Now the real thing. Send the order to the server, show progress while it's sending, and thank the customer when it's done.

  • Send the order
  • Show progress
  • Say thanks

useCheckout.js

Use checkout collects all the checkout logic in a custom hook. Submit validates first, and stops if there are errors. Then it sets sending, and waits for place order. When the order comes back, we store it, and clear the cart. Checkout shows a thank you message with the order number. We fill everything in, and pay. Run it.

useCheckout.jsjavascript
import { useState } from "react";
import { useCart } from "./CartContext";
import { placeOrder } from "./api";
import { validate } from "./validate";
export function useCheckout(form) {
  const { items, total, dispatch } = useCart();
  const [errors, setErrors] = useState({});
  const [order, setOrder] = useState(null);
  const [sending, setSending] = useState(false);
  async function submit(e) {
    e.preventDefault();
    const found = validate(form);
    if (Object.keys(found).length > 0) return setErrors(found);
    setSending(true);
    setOrder(await placeOrder({ ...form, items, total }));
    dispatch({ type: "clear" });
  }
  return { errors, order, sending, submit, total };
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses api.js
const PRODUCTS = [
  { id: 1, name: "Trail 500", price: 849.5, type: "bike", stock: 12 },
  { id: 2, name: "City 200", price: 450, type: "bike", stock: 0 },
  { id: 3, name: "Volt 7", price: 2199, type: "bike", stock: 4 },
  { id: 4, name: "Helmet", price: 40, type: "gear", stock: 30 },
  { id: 5, name: "Lights", price: 25, type: "gear", stock: 18 },
];
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
export const getProducts = () => wait(300).then(() => PRODUCTS);
export async function getProduct(id) {
  await wait(300);
  const product = PRODUCTS.find(p => p.id === Number(id));
  if (!product) throw new Error(`Product ${id} not found`);
  return product;
}
export async function placeOrder(order) {
  await wait(500);
  return { id: 1043, ...order };
}
Also uses shop.css
.box{padding:7px 12px;margin:5px 0} a{color:#0b6bcb} small{display:inline;margin-left:8px}
button:disabled{background:#ddd;color:#777}
header.box{display:flex;gap:14px;align-items:center;background:#eaf8fd}
Also uses cartReducer.js
export function cartReducer(items, action) {
  switch (action.type) {
    case "add": {
      const found = items.find(i => i.id === action.product.id);
      if (found) return items.map(i => (i.id === found.id ? { ...i, qty: i.qty + 1 } : i));
      return [...items, { ...action.product, qty: 1 }];
    }
    case "setQty":
      return items.map(i => (i.id === action.id ? { ...i, qty: action.qty } : i)).filter(i => i.qty > 0);
    case "clear":
      return [];
    default:
      throw new Error("Unknown action: " + action.type);
  }
}
Also uses Filters.jsx
export default function Filters({ query, setQuery, type, setType }) {
  return (
    <div>
      <input id="q" value={query} onChange={e => setQuery(e.target.value)} placeholder="Search" />{" "}
      <select id="type" value={type} onChange={e => setType(e.target.value)} style={{ fontSize: 19 }}>
        <option value="all">All</option><option value="bike">Bikes</option><option value="gear">Gear</option>
      </select>
    </div>
  );
}
Also uses Field.jsx
export default function Field({ name, label, form, setForm, errors }) {
  return (
    <label style={{ display: "block", margin: "6px 0" }}>
      {label} <input id={name} name={name} value={form[name]}
        onChange={e => setForm({ ...form, [name]: e.target.value })} />
      {errors[name] && <small>{errors[name]}</small>}
    </label>
  );
}
Also uses validate.js
export function validate(form) {
  const errors = {};
  if (!form.name.trim()) errors.name = "Please enter your name";
  if (!form.email.includes("@")) errors.email = "Please enter a valid email";
  if (form.address.trim().length < 5) errors.address = "Please enter your full address";
  return errors;
}
Also uses ProductPage.jsx
import { useState, useEffect } from "react";
import { useParams, Link } from "react-router";
import { getProduct } from "./api";
import { useCart } from "./CartContext";
export default function ProductPage() {
  const { id } = useParams();
  const { dispatch } = useCart();
  const [product, setProduct] = useState(null);
  const [error, setError] = useState(null);
  useEffect(() => {
    let ignore = false;
    getProduct(id).then(p => !ignore && setProduct(p)).catch(e => !ignore && setError(e.message));
    return () => { ignore = true; };
  }, [id]);
  if (error) return <p className="box">{error}. <Link to="/">Back to the shop</Link></p>;
  if (!product) return <p>Loading...</p>;
  return (<div className="box"><h2>{product.name}</h2><p>£{product.price} · {product.stock} in stock</p>
    <button id="addp" onClick={() => dispatch({ type: "add", product })}>Add to cart</button></div>);
}
Also uses NotFound.jsx
import { Link, useLocation } from "react-router";
export default function NotFound() {
  const { pathname } = useLocation();
  return (
    <div className="box">
      <h2>Page not found</h2>
      <p>Nothing lives at {pathname}.</p>
      <Link to="/">Back to the shop</Link>
    </div>
  );
}
Also uses pages.js
export { default as Layout } from "./Layout";
export { default as ProductList } from "./ProductList";
export { default as ProductPage } from "./ProductPage";
export { default as CartPanel } from "./CartPanel";
export { default as Checkout } from "./Checkout";
export { default as NotFound } from "./NotFound";
Also uses ProductCard.jsx
import { useCart } from "./CartContext";
export default function ProductCard({ product }) {
  const { dispatch } = useCart();
  const soldOut = product.stock === 0;
  return (
    <div className="box">
      <b>{product.name}</b> — £{product.price}{" "}
      <button id={"add" + product.id} disabled={soldOut} onClick={() => dispatch({ type: "add", product })}>
        {soldOut ? "Sold out" : "Add to cart"}
      </button>
    </div>
  );
}
Also uses ProductList.jsx
import { useState, useEffect } from "react";
import { getProducts } from "./api";
import ProductCard from "./ProductCard";
import Filters from "./Filters";
export default function ProductList() {
  const [products, setProducts] = useState(null);
  const [error, setError] = useState(null);
  const [query, setQuery] = useState("");
  const [type, setType] = useState("all");
  useEffect(() => { getProducts().then(setProducts).catch(e => setError(e.message)); }, []);
  if (error) return <small>Could not load products: {error}</small>;
  if (!products) return <p>Loading products...</p>;
  const shown = products.filter(p => (type === "all" || p.type === type)
    && p.name.toLowerCase().includes(query.toLowerCase()));
  return (<>
    <Filters query={query} setQuery={setQuery} type={type} setType={setType} />
    {shown.map(p => <ProductCard key={p.id} product={p} />)}
  </>);
}
Also uses CartContext.jsx
import { createContext, useContext, useEffect, useReducer } from "react";
import { cartReducer } from "./cartReducer";
const CartContext = createContext(null);
const load = () => JSON.parse(localStorage.getItem("cart") ?? "[]");
export function CartProvider({ children }) {
  const [items, dispatch] = useReducer(cartReducer, [], load);
  useEffect(() => localStorage.setItem("cart", JSON.stringify(items)), [items]);
  const count = items.reduce((n, i) => n + i.qty, 0);
  const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
  return <CartContext value={{ items, dispatch, count, total }}>{children}</CartContext>;
}
export const useCart = () => useContext(CartContext);
Also uses CartPanel.jsx
import { useCart } from "./CartContext";
export default function CartPanel() {
  const { items, dispatch, total } = useCart();
  if (items.length === 0) return <p className="box">Your cart is empty.</p>;
  const setQty = (id, qty) => dispatch({ type: "setQty", id, qty });
  return (
    <div className="box">
      <h2>Your cart</h2>
      {items.map(i => <div key={i.id}>
        <button id={"less" + i.id} onClick={() => setQty(i.id, i.qty - 1)}>−</button> {i.qty}
        <button id={"more" + i.id} onClick={() => setQty(i.id, i.qty + 1)}>+</button> {i.name} — £{(i.price * i.qty).toFixed(2)}
      </div>)}
      <p><b>Total: £{total.toFixed(2)}</b></p>
    </div>
  );
}
Also uses Checkout.jsx
import { useState } from "react";
import { useCheckout } from "./useCheckout";
import Field from "./Field";
export default function Checkout() {
  const [form, setForm] = useState({ name: "", email: "", address: "" });
  const { errors, order, sending, submit, total } = useCheckout(form);
  if (order) return <p className="box">Thanks, {form.name}! Order {order.id} is on its way.</p>;
  const props = { form, setForm, errors };
  return (
    <form onSubmit={submit} className="box">
      <Field name="name" label="Name" {...props} />
      <Field name="email" label="Email" {...props} />
      <Field name="address" label="Address" {...props} />
      <button id="place" disabled={sending}>{sending ? "Placing order..." : `Pay £${total.toFixed(2)}`}</button>
    </form>
  );
}
Also uses Layout.jsx
import { Link, Outlet } from "react-router";
import { useCart } from "./CartContext";
export default function Layout() {
  const { count } = useCart();
  return (<>
    <header className="box">
      <Link to="/"><b>Northwind Bikes</b></Link>
      <Link id="cartlink" to="/cart">Cart ({count})</Link>
    </header>
    <main><Outlet /></main>
  </>);
}
Also uses App.jsx
import "./shop.css";
import { CartProvider, useCart } from "./CartContext";
import ProductList from "./ProductList";
import CartPanel from "./CartPanel";
import Checkout from "./Checkout";
if (!localStorage.getItem("cart")) localStorage.setItem("cart", JSON.stringify([{ id: 4, name: "Helmet", price: 40, qty: 1 }]));
function Header() {
  const { count } = useCart();
  return <header className="box"><b>Northwind Bikes</b> Cart ({count})</header>;
}
export default function App() {
  return <CartProvider><Header /><main><Checkout /></main></CartProvider>;
}
Also uses actions.json
[{"wait": 400}, {"type": "#name", "text": "Priya Shah"}, {"type": "#email", "text": "priya@example.com"}, {"type": "#address", "text": "12 Park Road, Leeds"}, {"click": "#place"}, {"wait": 900}]

Summary

Use checkout validates, sends the order, and clears the cart. Next, real pages with routing.

Key takeaways
  • async submit
  • sending
  • Clear the cart
Next up: Project: Pages — routing