Skip to the code

An order status that keeps itself up to date

A customer's order page at Leaf and Kettle, /orders/1042, is a Server Component that loads the order and renders LiveStatus with its status: placed, packed, shipped, or delivered. Customers leave the page open while they wait, and want to see the parcel move without reloading. Write app/orders/[id]/live-status.tsx, a Client Component whose default export is LiveStatus({ status }).

Show the steps as an ordered list, Placed, Packed, Shipped, Delivered, with aria-current="step" on the order's current step. Under the list, show We'll check for updates every 15 seconds., or Delivered. Enjoy your tea! once the status is delivered.

To check, call router.refresh(), from useRouter() in next/navigation, every 15 seconds. It asks the server to render the page's Server Components again and merges the result into the page without losing any Client Component's state: when the order has moved on, LiveStatus just gets a new status prop.

Stop checking once the status is delivered, and when the component leaves the page. Don't check while the tab is hidden (document.visibilityState is "hidden"): when it's visible again, which document announces with a visibilitychange event, check at once, then every 15 seconds from then.

<LiveStatus status="packed" />
Placed  Packed (aria-current="step")  Shipped  Delivered
We'll check for updates every 15 seconds.
 
15 s, 30 s, 45 s…      router.refresh()
tab hidden             no refreshes
tab visible again      router.refresh() at once, then every 15 s
status="delivered"     Delivered. Enjoy your tea!   (no more refreshes)

The app's other files

lib/orders.ts, read-only. Import it as @/lib/orders.

export type OrderStatus = "placed" | "packed" | "shipped" | "delivered";
export type Order = { id: string; status: OrderStatus };
 
/** The customer's orders: a stand-in for the shop's database. */
export const orders: Order[] = [
  { id: "1042", status: "packed" },
  { id: "1043", status: "delivered" },
];
 
/** The order with this id, or undefined when there's none. */
export async function getOrder(id: string): Promise<Order | undefined> {
  const order = orders.find((entry) => entry.id === id);
  return order && { ...order };
}

app/orders/[id]/page.tsx, read-only. Import it as @/app/orders/[id]/page.

import { notFound } from "next/navigation";
import { getOrder } from "@/lib/orders";
import LiveStatus from "./live-status";
 
export default async function OrderPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const order = await getOrder(id);
  if (!order) notFound();
 
  return (
    <main>
      <h1>Order {order.id}</h1>
      <LiveStatus status={order.status} />
    </main>
  );
}

What the tests check

  1. is a Client Component the order page shows, with the current step marked
    const renderOnServer = async (element, options) => {
      try {
        return await renderServer(element, options);
      } catch (error) {
        if (/reading 'use[A-Za-z]*'/.test(String(error && error.message))) {
          throw new Error('A component that calls hooks ran as a Server Component, where there are none. Does its file start with "use client"? (' + error.message + ")");
        }
        throw error;
      }
    };
    const refreshes = () => router.calls.filter((call) => call.method === "refresh").length;
    let visibility = "visible";
    Object.defineProperty(document, "visibilityState", { configurable: true, get: () => visibility });
    Object.defineProperty(document, "hidden", { configurable: true, get: () => visibility === "hidden" });
    const setVisibility = async (value) => {
      visibility = value;
      await act(async () => {
        document.dispatchEvent(new Event("visibilitychange"));
      });
    };
    const currentStep = () => screen.getAllByRole("listitem").filter((item) => item.getAttribute("aria-current") === "step").map((item) => item.textContent);
    await renderOnServer(<Page params={params({ id: "1042" })} />);
    expect(screen.getByRole("heading", { level: 1, name: "Order 1042" })).toBeInTheDocument();
    expect(screen.getAllByRole("listitem").map((item) => item.textContent)).toEqual(["Placed", "Packed", "Shipped", "Delivered"]);
    expect(currentStep()).toEqual(["Packed"]);
    expect(screen.getByText("We'll check for updates every 15 seconds.")).toBeInTheDocument();
    
  2. refreshes the page every 15 seconds
    const refreshes = () => router.calls.filter((call) => call.method === "refresh").length;
    let visibility = "visible";
    Object.defineProperty(document, "visibilityState", { configurable: true, get: () => visibility });
    Object.defineProperty(document, "hidden", { configurable: true, get: () => visibility === "hidden" });
    const setVisibility = async (value) => {
      visibility = value;
      await act(async () => {
        document.dispatchEvent(new Event("visibilitychange"));
      });
    };
    const currentStep = () => screen.getAllByRole("listitem").filter((item) => item.getAttribute("aria-current") === "step").map((item) => item.textContent);
    const clock = useFakeTimers();
    render(<LiveStatus status="packed" />);
    await clock.advance(14999);
    expect(refreshes()).toBe(0);
    await clock.advance(1);
    expect(refreshes()).toBe(1);
    await clock.advance(30000);
    expect(refreshes()).toBe(3);
    
  3. shows the new status a refresh brings, and keeps checking
    const refreshes = () => router.calls.filter((call) => call.method === "refresh").length;
    let visibility = "visible";
    Object.defineProperty(document, "visibilityState", { configurable: true, get: () => visibility });
    Object.defineProperty(document, "hidden", { configurable: true, get: () => visibility === "hidden" });
    const setVisibility = async (value) => {
      visibility = value;
      await act(async () => {
        document.dispatchEvent(new Event("visibilitychange"));
      });
    };
    const currentStep = () => screen.getAllByRole("listitem").filter((item) => item.getAttribute("aria-current") === "step").map((item) => item.textContent);
    const clock = useFakeTimers();
    const view = render(<LiveStatus status="packed" />);
    await clock.advance(15000);
    expect(refreshes()).toBe(1);
    // The refresh came back with the order shipped: Next.js passes the new prop.
    view.rerender(<LiveStatus status="shipped" />);
    expect(currentStep()).toEqual(["Shipped"]);
    await clock.advance(15000);
    expect(refreshes()).toBe(2);
    
  4. stops checking once the order is delivered
    const refreshes = () => router.calls.filter((call) => call.method === "refresh").length;
    let visibility = "visible";
    Object.defineProperty(document, "visibilityState", { configurable: true, get: () => visibility });
    Object.defineProperty(document, "hidden", { configurable: true, get: () => visibility === "hidden" });
    const setVisibility = async (value) => {
      visibility = value;
      await act(async () => {
        document.dispatchEvent(new Event("visibilitychange"));
      });
    };
    const currentStep = () => screen.getAllByRole("listitem").filter((item) => item.getAttribute("aria-current") === "step").map((item) => item.textContent);
    const clock = useFakeTimers();
    const view = render(<LiveStatus status="shipped" />);
    await clock.advance(15000);
    view.rerender(<LiveStatus status="delivered" />);
    expect(currentStep()).toEqual(["Delivered"]);
    expect(screen.getByText("Delivered. Enjoy your tea!")).toBeInTheDocument();
    expect(screen.queryByText(/every 15 seconds/)).not.toBeInTheDocument();
    await clock.advance(60000);
    await setVisibility("hidden");
    await setVisibility("visible");
    expect(refreshes()).toBe(1);
    cleanup();
    render(<LiveStatus status="delivered" />);
    await clock.advance(60000);
    expect(refreshes()).toBe(1);
    
  5. doesn't refresh while the tab is hidden, and refreshes at once when it's back
    const refreshes = () => router.calls.filter((call) => call.method === "refresh").length;
    let visibility = "visible";
    Object.defineProperty(document, "visibilityState", { configurable: true, get: () => visibility });
    Object.defineProperty(document, "hidden", { configurable: true, get: () => visibility === "hidden" });
    const setVisibility = async (value) => {
      visibility = value;
      await act(async () => {
        document.dispatchEvent(new Event("visibilitychange"));
      });
    };
    const currentStep = () => screen.getAllByRole("listitem").filter((item) => item.getAttribute("aria-current") === "step").map((item) => item.textContent);
    const clock = useFakeTimers();
    render(<LiveStatus status="packed" />);
    await clock.advance(5000);
    await setVisibility("hidden");
    await clock.advance(60000);
    expect(refreshes()).toBe(0);
    await setVisibility("visible");
    expect(refreshes()).toBe(1);
    await clock.advance(14999);
    expect(refreshes()).toBe(1);
    await clock.advance(1);
    expect(refreshes()).toBe(2);
    
  6. stops when the customer leaves the page
    const refreshes = () => router.calls.filter((call) => call.method === "refresh").length;
    let visibility = "visible";
    Object.defineProperty(document, "visibilityState", { configurable: true, get: () => visibility });
    Object.defineProperty(document, "hidden", { configurable: true, get: () => visibility === "hidden" });
    const setVisibility = async (value) => {
      visibility = value;
      await act(async () => {
        document.dispatchEvent(new Event("visibilitychange"));
      });
    };
    const currentStep = () => screen.getAllByRole("listitem").filter((item) => item.getAttribute("aria-current") === "step").map((item) => item.textContent);
    const clock = useFakeTimers();
    const view = render(<LiveStatus status="placed" />);
    await clock.advance(15000);
    view.unmount();
    await clock.advance(60000);
    await setVisibility("hidden");
    await setVisibility("visible");
    expect(refreshes()).toBe(1);
    

Learn more

app/orders/[id]/live-status.tsxSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).