Course progress0%
Course content
40 min

Where Does the Current Order Live?

Keep one authoritative in-memory draft

By the end of this lesson

  • Keep one authoritative in-memory draft
  • Distinguish input state, derived results and presentation

The contradiction

A quantity input shows 2 but the total still represents quantity 1. Which value should the user trust? This is a state-consistency problem, not a CSS problem.

Keep one draft object in application memory. Treat the quote as a derived result and the DOM as its presentation. A small state record can also say whether the displayed result is current.

export function changeQuantity(state, quantity) {
  if (state.order.status !== 'draft') throw new Error('Only drafts can be edited');
  return {
    ...state,
    order: {
      ...state.order,
      items: state.order.items.map((item, index) =>
        index === 0 ? { ...item, quantity } : item)
    },
    quote: null,
    phase: 'dirty'
  };
}

This is a one-item exercise operation: it updates only the first item. The order now has an additional status property, initially draft; Course 02's quote function can ignore that property. Copying the affected object and item keeps an earlier snapshot intact. We will validate raw form text in the next module.

Phase describes interface state such as dirty or ready. Status describes business state such as draft or confirmed. Do not combine them into one field: a draft may be loading a quote, and a confirmed order may be loading a read-only view.

Guided trace

Write the values after each action: load baseline, calculate, change quantity, calculate again. After the edit, the old quote must be cleared or visibly marked outdated. In this course we hide it until recalculation.

Build it yourself

Create state.js containing your initial state and update functions. Let main.js hold the current state. Update it in response to an action, then render. Keep your format function out of state: numbers stay numeric and display strings are derived later.

Test that the old state's quantity remains 1 after creating a new state with quantity 2. Also verify that quote is cleared. For the premium 150-unit item, the new subtotal is 300.00, discount 30.00, tax 54.00 and total 324.00.

Counterexample

An object copy alone does not copy nested items. { ...state } followed by changing state.order.items[0] still mutates shared nested data. Trace the references and copy the path you intentionally change.

Change request and correction

"Keep two draft quotes open." Give each draft its own id and state entry rather than adding global variables such as quantity2. The underlying update operation should identify the draft and item it affects. Do not build multi-draft support yet; explain the model you would need.

Lesson complete?

Your progress is saved on this device.