Leaf and Kettle's staff dashboard, app/admin/page.tsx, shows three panels, each from its own service in @/lib/dashboard: getTodaysOrders() (200 ms), getLowStock() (600 ms), and getLatestReviews() (400 ms). Today it awaits all three in turn, so staff stare at nothing for over a second, and when one service fails the whole page fails. Make each panel show as soon as its own data arrives, and keep a failure inside its panel.
Render an <h1> with Shop dashboard, then three <section>s in this order, each starting with its <h2>: Today's orders, Low stock, and Latest reviews.
Today's orders shows a paragraph like 3 orders, $50.75, the count and the total with two decimals, 1 order for one, and No orders yet today. for none. Low stock is a list with an item like Mint tea: 3 left for each tea, or Everything is well stocked. Latest reviews is a list with an item like Kenji on Sencha: Fresh, like spring. for each review, or No reviews yet.
Under each heading, load the panel's data in an async Server Component of its own, wrapped in <Suspense> with a paragraph as its fallback, Loading today's orders…, Loading low stock…, or Loading latest reviews…. Wrap that in PanelBoundary from ./panel-boundary, a Client Component error boundary, with the panel's name: today's orders, low stock, or latest reviews. When a panel's query fails, its boundary shows Couldn't load low stock. and a Try again button in that panel, under its heading, while the other panels show their data.
0 ms Shop dashboard
Today's orders: Loading today's orders… Low stock: Loading low stock… Latest reviews: Loading latest reviews…
200 ms Today's orders: 3 orders, $50.75
400 ms Latest reviews: Kenji on Sencha: Fresh, like spring. Ana on Masala chai: Warming and bold.
600 ms Low stock: Oolong tea: 1 left Mint tea: 3 left
(or, if the stock service fails: Couldn't load low stock. [Try again])
lib/dashboard.ts, read-only. Import it as @/lib/dashboard.
export type Order = { id: string; total: number };
export type LowStockTea = { slug: string; name: string; left: number };
export type Review = { id: string; author: string; tea: string; text: string };
/** Today's orders, the teas running low, and the newest reviews: a stand-in for the shop's services. */
export const orders: Order[] = [
{ id: "o1", total: 12.5 },
{ id: "o2", total: 30 },
{ id: "o3", total: 8.25 },
];
export const lowStock: LowStockTea[] = [
{ slug: "oolong", name: "Oolong tea", left: 1 },
{ slug: "mint", name: "Mint tea", left: 3 },
];
export const reviews: Review[] = [
{ id: "r1", author: "Kenji", tea: "Sencha", text: "Fresh, like spring." },
{ id: "r2", author: "Ana", tea: "Masala chai", text: "Warming and bold." },
];
/** The queries that have started, in order: what the services would see. */
export const started: string[] = [];
/** Set one to true and its query fails, as a busy service sometimes does. */
export const down = { orders: false, stock: false, reviews: false };
/** How long each service takes to answer. */
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
/** Today's orders. Takes 200 ms. */
export async function getTodaysOrders(): Promise<Order[]> {
started.push("orders");
await wait(200);
if (down.orders) throw new Error("The orders database timed out.");
return orders.map((order) => ({ ...order }));
}
/** The teas with fewer than 5 left, fewest first. The stock service is slow: 600 ms. */
export async function getLowStock(): Promise<LowStockTea[]> {
started.push("stock");
await wait(600);
if (down.stock) throw new Error("The stock service is unavailable.");
return lowStock.map((tea) => ({ ...tea }));
}
/** The newest reviews. Takes 400 ms. */
export async function getLatestReviews(): Promise<Review[]> {
started.push("reviews");
await wait(400);
if (down.reviews) throw new Error("The reviews service returned 503.");
return reviews.map((review) => ({ ...review }));
}
app/admin/panel-boundary.tsx, read-only. Import it as @/app/admin/panel-boundary.
"use client";
import { Component, startTransition, type ReactNode } from "react";
import { useRouter } from "next/navigation";
type BoundaryProps = { name: string; onRetry: () => void; children: ReactNode };
class Boundary extends Component<BoundaryProps, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
retry = () => {
// Ask the server for the page again, and show the panel's children again with what comes back.
startTransition(() => {
this.props.onRetry();
this.setState({ failed: false });
});
};
render() {
if (!this.state.failed) return this.props.children;
return (
<>
<p role="alert">Couldn't load {this.props.name}.</p>
<button type="button" onClick={this.retry}>
Try again
</button>
</>
);
}
}
/**
* An error boundary around one panel: when anything inside it fails, it says so (never with the
* error's own message) and offers Try again, which fetches the page's Server Components again.
* catchError from next/error makes the same kind of boundary, with retry() built in.
*/
export default function PanelBoundary({ name, children }: { name: string; children: ReactNode }) {
const router = useRouter();
return (
<Boundary name={name} onRetry={() => router.refresh()}>
{children}
</Boundary>
);
}
// Renders the page the way Next.js streams it: each Server Component shows once its data has
// arrived, a <Suspense> shows its fallback until everything inside it has, and PanelBoundary, a
// Client Component, runs as it would in the browser.
const Await = ({ promise }) => React.use(promise);
const streamed = (node) => {
if (Array.isArray(node)) return node.map(streamed);
if (!React.isValidElement(node)) return node;
if (typeof node.type === "function" && node.type !== PanelBoundary) {
return <Await key={node.key} promise={Promise.resolve().then(() => node.type(node.props)).then(streamed)} />;
}
const { children, fallback } = node.props;
const props = fallback === undefined ? {} : { fallback: streamed(fallback) };
return children === undefined ? React.cloneElement(node, props) : React.cloneElement(node, props, ...[].concat(streamed(children)));
};
const clock = useFakeTimers();
const open = async () => {
await settle(async () => {
render(streamed(<Page />));
});
await flush();
};
const panel = (name) => {
const heading = screen.getByRole("heading", { level: 2, name });
const section = heading.closest("section");
if (!section) throw new Error('The "' + name + '" heading should be inside its panel\'s <section>.');
return within(section);
};
const items = (name) => panel(name).queryAllByRole("listitem").map((item) => item.textContent);
await open();
expect(screen.getByRole("heading", { level: 1, name: "Shop dashboard" })).toBeInTheDocument();
expect(panel("Today's orders").getByText("Loading today's orders…")).toBeInTheDocument();
expect(panel("Low stock").getByText("Loading low stock…")).toBeInTheDocument();
expect(panel("Latest reviews").getByText("Loading latest reviews…")).toBeInTheDocument();
await clock.advance(200);
expect(panel("Today's orders").getByText("3 orders, $50.75")).toBeInTheDocument();
expect(panel("Low stock").getByText("Loading low stock…")).toBeInTheDocument();
await clock.advance(200);
expect(items("Latest reviews")).toEqual(["Kenji on Sencha: Fresh, like spring.", "Ana on Masala chai: Warming and bold."]);
expect(panel("Low stock").getByText("Loading low stock…")).toBeInTheDocument();
await clock.advance(200);
expect(items("Low stock")).toEqual(["Oolong tea: 1 left", "Mint tea: 3 left"]);
expect(screen.queryByText(/^Loading/)).not.toBeInTheDocument();
// Renders the page the way Next.js streams it: each Server Component shows once its data has
// arrived, a <Suspense> shows its fallback until everything inside it has, and PanelBoundary, a
// Client Component, runs as it would in the browser.
const Await = ({ promise }) => React.use(promise);
const streamed = (node) => {
if (Array.isArray(node)) return node.map(streamed);
if (!React.isValidElement(node)) return node;
if (typeof node.type === "function" && node.type !== PanelBoundary) {
return <Await key={node.key} promise={Promise.resolve().then(() => node.type(node.props)).then(streamed)} />;
}
const { children, fallback } = node.props;
const props = fallback === undefined ? {} : { fallback: streamed(fallback) };
return children === undefined ? React.cloneElement(node, props) : React.cloneElement(node, props, ...[].concat(streamed(children)));
};
const clock = useFakeTimers();
const open = async () => {
await settle(async () => {
render(streamed(<Page />));
});
await flush();
};
const panel = (name) => {
const heading = screen.getByRole("heading", { level: 2, name });
const section = heading.closest("section");
if (!section) throw new Error('The "' + name + '" heading should be inside its panel\'s <section>.');
return within(section);
};
const items = (name) => panel(name).queryAllByRole("listitem").map((item) => item.textContent);
await open();
expect([...started].sort()).toEqual(["orders", "reviews", "stock"]);
await clock.advance(600);
expect(panel("Today's orders").getByText("3 orders, $50.75")).toBeInTheDocument();
expect(items("Low stock")).toHaveLength(2);
expect(items("Latest reviews")).toHaveLength(2);
// Renders the page the way Next.js streams it: each Server Component shows once its data has
// arrived, a <Suspense> shows its fallback until everything inside it has, and PanelBoundary, a
// Client Component, runs as it would in the browser.
const Await = ({ promise }) => React.use(promise);
const streamed = (node) => {
if (Array.isArray(node)) return node.map(streamed);
if (!React.isValidElement(node)) return node;
if (typeof node.type === "function" && node.type !== PanelBoundary) {
return <Await key={node.key} promise={Promise.resolve().then(() => node.type(node.props)).then(streamed)} />;
}
const { children, fallback } = node.props;
const props = fallback === undefined ? {} : { fallback: streamed(fallback) };
return children === undefined ? React.cloneElement(node, props) : React.cloneElement(node, props, ...[].concat(streamed(children)));
};
const clock = useFakeTimers();
const open = async () => {
await settle(async () => {
render(streamed(<Page />));
});
await flush();
};
const panel = (name) => {
const heading = screen.getByRole("heading", { level: 2, name });
const section = heading.closest("section");
if (!section) throw new Error('The "' + name + '" heading should be inside its panel\'s <section>.');
return within(section);
};
const items = (name) => panel(name).queryAllByRole("listitem").map((item) => item.textContent);
down.reviews = true;
await open();
await clock.advance(600);
expect(panel("Latest reviews").getByRole("alert")).toHaveTextContent("Couldn't load latest reviews.");
expect(panel("Latest reviews").getByRole("button", { name: "Try again" })).toBeInTheDocument();
expect(screen.getAllByRole("alert")).toHaveLength(1);
expect(panel("Today's orders").getByText("3 orders, $50.75")).toBeInTheDocument();
expect(items("Low stock")).toEqual(["Oolong tea: 1 left", "Mint tea: 3 left"]);
expect(screen.queryByText(/503/)).not.toBeInTheDocument();
// Renders the page the way Next.js streams it: each Server Component shows once its data has
// arrived, a <Suspense> shows its fallback until everything inside it has, and PanelBoundary, a
// Client Component, runs as it would in the browser.
const Await = ({ promise }) => React.use(promise);
const streamed = (node) => {
if (Array.isArray(node)) return node.map(streamed);
if (!React.isValidElement(node)) return node;
if (typeof node.type === "function" && node.type !== PanelBoundary) {
return <Await key={node.key} promise={Promise.resolve().then(() => node.type(node.props)).then(streamed)} />;
}
const { children, fallback } = node.props;
const props = fallback === undefined ? {} : { fallback: streamed(fallback) };
return children === undefined ? React.cloneElement(node, props) : React.cloneElement(node, props, ...[].concat(streamed(children)));
};
const clock = useFakeTimers();
const open = async () => {
await settle(async () => {
render(streamed(<Page />));
});
await flush();
};
const panel = (name) => {
const heading = screen.getByRole("heading", { level: 2, name });
const section = heading.closest("section");
if (!section) throw new Error('The "' + name + '" heading should be inside its panel\'s <section>.');
return within(section);
};
const items = (name) => panel(name).queryAllByRole("listitem").map((item) => item.textContent);
down.stock = true;
down.orders = true;
await open();
await clock.advance(400);
expect(panel("Today's orders").getByRole("alert")).toHaveTextContent("Couldn't load today's orders.");
expect(items("Latest reviews")).toHaveLength(2);
expect(panel("Low stock").getByText("Loading low stock…")).toBeInTheDocument();
await clock.advance(200);
expect(panel("Low stock").getByRole("alert")).toHaveTextContent("Couldn't load low stock.");
await user.click(panel("Low stock").getByRole("button", { name: "Try again" }));
expect(router.calls).toEqual([{ method: "refresh" }]);
// Renders the page the way Next.js streams it: each Server Component shows once its data has
// arrived, a <Suspense> shows its fallback until everything inside it has, and PanelBoundary, a
// Client Component, runs as it would in the browser.
const Await = ({ promise }) => React.use(promise);
const streamed = (node) => {
if (Array.isArray(node)) return node.map(streamed);
if (!React.isValidElement(node)) return node;
if (typeof node.type === "function" && node.type !== PanelBoundary) {
return <Await key={node.key} promise={Promise.resolve().then(() => node.type(node.props)).then(streamed)} />;
}
const { children, fallback } = node.props;
const props = fallback === undefined ? {} : { fallback: streamed(fallback) };
return children === undefined ? React.cloneElement(node, props) : React.cloneElement(node, props, ...[].concat(streamed(children)));
};
const clock = useFakeTimers();
const open = async () => {
await settle(async () => {
render(streamed(<Page />));
});
await flush();
};
const panel = (name) => {
const heading = screen.getByRole("heading", { level: 2, name });
const section = heading.closest("section");
if (!section) throw new Error('The "' + name + '" heading should be inside its panel\'s <section>.');
return within(section);
};
const items = (name) => panel(name).queryAllByRole("listitem").map((item) => item.textContent);
orders.splice(1);
lowStock.length = 0;
reviews.length = 0;
await open();
await clock.advance(600);
expect(panel("Today's orders").getByText("1 order, $12.50")).toBeInTheDocument();
expect(panel("Low stock").getByText("Everything is well stocked.")).toBeInTheDocument();
expect(panel("Latest reviews").getByText("No reviews yet.")).toBeInTheDocument();
expect(screen.queryByRole("list")).not.toBeInTheDocument();
cleanup();
orders.length = 0;
await open();
await clock.advance(600);
expect(panel("Today's orders").getByText("No orders yet today.")).toBeInTheDocument();
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).
I'm here to help with A dashboard whose panels load and fail on their own. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.