The loopLesson 10 of 23

How does state change?

Write update by hand, fold a list of messages into a state, and replay it.

The last lesson drew a screen from a Model, and nothing could change it. Before putting buttons on it, work out what "changing state" should mean. There is no UI in this lesson, only a few lines of plain TypeScript.

Predict

Read main.ts. session is a list of things somebody did to a counter. program walks the list and passes each one through update. What is the last line it logs?

Check your answer

ClickedIncrement -> {"count":2}. Up, up, down, up. Press Run and check each step against the list.

Try it

  1. Delete the third message from session. Before you run: what is the final count now? What did you have to read to know?

  2. Look for the place where the current state is stored between sessions. Where is it?

  3. Replace the loop with one line: return session.reduce(update, init). Same answer?

  4. Write const replay = (messages: ReadonlyArray<Message>) => messages.reduce(update, init), and log replay(session.slice(0, 2)). What is that value, in words?

  5. Add a third thing that can happen, ClickedReset, and put one in the middle of the session. What do the messages after it start from?

About steps 2 and 4

It isn't stored anywhere. The state is whatever you get by running the messages through update, in order, starting from init. That is why step 1 needed nothing but the list.

And replay(session.slice(0, 2)) is the state as it was after the second message. Going back in time is taking a shorter list.

What you found

update has the shape (model, message) => model. It takes the state and one thing that happened, and returns the next state. It doesn't change anything, read a clock or touch a screen, so the same inputs always give the same output.

Running a list through a function like that is called a fold, and reduce is JavaScript's name for it. So a state is a fold of the messages so far. Three things follow at once. You can rebuild any state from its messages. You can see any earlier state by stopping early. And a bug report can be a list.

This loop is a user interface's whole engine, minus the screen. You wrote it by hand to see that there is nothing hidden in it. From here on a runtime runs it for you: it keeps the Model, calls update when a message arrives and draws the result. What it needs from you is the next thing to work out. Where do messages come from?

10
Principle 10

State is a fold of facts

The Model is what you get by running every message, in order, through update. Keep the messages and you can rebuild, replay or inspect any moment.

OutputNot run yet

Not run yet

Read the code and say what it will do. Then press Run.