completefrontend

Write the codeMedium

Write a context provider that shares the signed-in customer with Client Components, without making the pages wait

The shop's layout, a Server Component, starts getCustomer() without awaiting it, so the pages render while the customer loads, and passes the promise to CustomerProvider. Client Components anywhere below, like the header's greeting and a points badge inside the tea list page, read the customer with useCustomer(), each inside its own <Suspense>.

Write app/customer-provider.tsx. Its default export, CustomerProvider({ customer, children }), takes the promise and the children. useCustomer() returns the customer, { name, points }, or null for a visitor who isn't signed in, suspending until it has loaded. Only the components that call useCustomer() may wait: the pages around them must render straight away.

Outside a CustomerProvider, useCustomer() throws an Error with the message useCustomer must be used inside a CustomerProvider.

Write this: app/customer-provider.tsx
"use client";
 
import { createContext, use, useContext, type ReactNode } from "react";
import type { Customer } from "@/lib/customers";
 
const CustomerContext = createContext<Customer | null>(null);
 
export default function CustomerProvider({ customer, children }: { customer: Promise<Customer | null>; children: ReactNode }) {
  return <CustomerContext value={use(customer)}>{children}</CustomerContext>;
}
 
export function useCustomer() {
  return useContext(CustomerContext);
}
lib/customers.ts (read-only)
import "server-only";
 
export type Customer = { name: string; points: number };
 
/** Who's signed in for this request. A real shop reads the session cookie; the tests change this. */
export const session: { customer: Customer | null } = { customer: { name: "Ana", points: 120 } };
 
/** Every lookup the customers database was asked for. */
export const lookups: string[] = [];
 
/** How long the customers database takes to answer. */
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
 
/** The signed-in customer, or null for a visitor who isn't signed in. Takes 300 ms. */
export async function getCustomer(): Promise<Customer | null> {
  lookups.push("customer");
  await wait(300);
  return session.customer;
}
app/(shop)/layout.tsx (read-only)
import { Suspense, type ReactNode } from "react";
import { getCustomer } from "@/lib/customers";
import CustomerProvider from "../customer-provider";
import Greeting from "../components/greeting";
 
export default function ShopLayout({ children }: { children: ReactNode }) {
  // Started here and not awaited: the pages render while the customer loads.
  const customer = getCustomer();
 
  return (
    <CustomerProvider customer={customer}>
      <header>
        <Suspense fallback={<p>Welcome to Leaf and Kettle</p>}>
          <Greeting />
        </Suspense>
      </header>
      <main>{children}</main>
    </CustomerProvider>
  );
}
app/(shop)/teas/page.tsx (read-only)
import { Suspense } from "react";
import PointsBadge from "../../components/points-badge";
 
export default function TeasPage() {
  return (
    <>
      <h1>Our teas</h1>
      <Suspense fallback={null}>
        <PointsBadge />
      </Suspense>
      <ul>
        <li>Green tea</li>
        <li>Oolong tea</li>
      </ul>
    </>
  );
}
app/components/greeting.tsx (read-only)
"use client";
 
import { useCustomer } from "../customer-provider";
 
export default function Greeting() {
  const customer = useCustomer();
  if (!customer) return <a href="/sign-in">Sign in</a>;
  return (
    <p>
      Welcome back, {customer.name}. You have {customer.points} points.
    </p>
  );
}
app/components/points-badge.tsx (read-only)
"use client";
 
import { useCustomer } from "../customer-provider";
 
export default function PointsBadge() {
  const customer = useCustomer();
  return customer ? <p>{customer.points} points to spend</p> : null;
}
The tests your code must pass
  • is a Client Component around the shop's pages, and doesn't hold them up
  • gives every Client Component below it the customer once it has loaded
  • gives null for a visitor who isn't signed in
  • only the components that read the customer wait for it
  • useCustomer outside a CustomerProvider throws a clear error

Try it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…