Dev Helpers
← Back

Compute a running invoice subtotal

Compute a running invoice subtotal. Build the result in an App Router server page and send the rendered entries to the client.

Open this example in the interactive library

Source code

// app/compute-a-running-invoice-subtotal/page.tsx
export const metadata = { title: "Compute a running invoice subtotal" };
export default function Page() {
  const rows = [
    { item: "tea", units: 2, cents: 350 },
    { item: "mug", units: 1, cents: 900 },
    { item: "tea", units: 3, cents: 325 },
    { item: "tin", units: 2, cents: 500 },
  ];
  const result = rows.map((r, i) => ({
    item: r.item,
    subtotalCents: rows
      .slice(0, i + 1)
      .reduce((s, x) => s + x.units * x.cents, 0),
  }));
  const entries = Object.entries(
    typeof result === "object" && result !== null ? result : { value: result },
  );
  return (
    <section>
      <h2>{"Compute a running invoice subtotal"}</h2>
      {entries.length ? (
        <dl>
          {entries.map(([key, value]) => (
            <div key={key}>
              <dt>{key}</dt>
              <dd>
                {typeof value === "string" ? value : JSON.stringify(value)}
              </dd>
            </div>
          ))}
        </dl>
      ) : (
        <p>No matching entries.</p>
      )}
    </section>
  );
}