CodingNic

Client State and Rendering

Calculate the Monthly Summary in One Place

Client State and Rendering 20 min read

Calculate the Monthly Summary in One Place

Open these files:

text
client/src/components/SummaryStrip.jsx
client/src/lib/finance.js

The summary strip should render values, not become the place where every financial rule is invented. Move the arithmetic into a small reusable function so other screens can use exactly the same rules later.

Add this function to client/src/lib/finance.js:

javascript
export function calculateTotals(transactions) {
  return transactions.reduce(
    (totals, transaction) => {
      if (transaction.type === "income") {
        totals.income += transaction.amount;
      }

      if (transaction.type === "expense") {
        totals.expense += transaction.amount;
      }

      return totals;
    },
    { income: 0, expense: 0 }
  );
}

At this point in the course, the starter stores money in the amount field, so this function uses that field. Later, in the API hardening module, we will deliberately change the stored representation to integer cents. The calculation will then change from amount to amountCents, but the responsibility of the function will stay the same.

In SummaryStrip.jsx, use the month’s transactions as the input:

javascript
const monthTx = useMonthTransactions();
const { income, expense } = calculateTotals(monthTx);
const balance = income - expense;

Then format those values for display.

What the calculation is doing

reduce() walks through every transaction and keeps a running pair of totals.

An income transaction contributes to incomeCents.

An expense transaction contributes to expenseCents.

The function deliberately does not calculate a balance itself. Balance is a direct relationship between the two totals:

text
balance = income - expenses

Keeping that relationship obvious makes the rule easier to reuse and test.

Test it

With the sample September data, compare the summary strip with the transactions shown below it.

Move to another month and confirm the three displayed values change with the month’s records rather than staying fixed.

Checkpoint

The summary strip receives monthly transactions, delegates the arithmetic to finance.js, and displays income, expenses, and balance without duplicating the calculation in the component.