The loopLesson 9 of 23

What decides what's on screen?

Draw a screen from state, and find out what a view can't do.

The first eight lessons were about programs. Now point the same idea at a screen. On the right is the smallest component there is: it remembers one thing and draws it.

Predict

Read Hello.ts. init returns the Model the component starts with, and view is handed that Model.

Change init in your head so the name is "Ada". What does the screen say? And is there any line in view that could change the name to something else?

Check your answer

It says "Hello, Ada!", and no, there isn't.

view reads model.name and builds a heading from it. It has no way to write to the Model. It gets the Model as an argument and gives back elements, and that is all it does.

Try it

  1. Change the name in init to your own and press Run. Which function did you not have to touch?

  2. Open the init row in the log beside the result. What is in it?

  3. Add visits: Schema.Number to the Model's Schema, and visits: 3 to init. Before you run: will the screen look any different?

  4. Now draw it. Add a third child to the div:

    h.p(
      "You have been here ",
      h.span.class("pill").children(String(model.visits)),
      " times."
    )
  5. h.p(...) is called inside view. When that line runs, is a paragraph added to the page?

About steps 3 and 5

In step 3 the screen doesn't change. The Model holds more, but the screen shows only what view draws from it.

In step 5, no. h.p(...) builds a description of a paragraph, the way Effect.sync built a description of work in lesson 1. view returns a description of the whole screen, and the runtime does the drawing.

What you found

A component starts with two things. The Model is everything it remembers, described with a Schema, as in the last lesson. view is a function from that Model to a description of the screen.

So the screen is a function of state. Give view the same Model and you get the same screen. To know what is on screen you need to know one value, and you just read it in the log.

It is the idea from lesson 1 again. You describe, and something else does. There the description was a program and the sandbox ran it. Here it is a screen, and the runtime draws it and keeps it drawn.

This component is stuck, though. message is Schema.Never, so nothing can happen to it, and update hands the Model back untouched. Before adding a button, ask the plainer question. What should it even mean for state to change?

09
Principle 9

The screen is a function of state

view takes the Model and returns a description of the screen. It can't change the Model. It can only draw it.

ResultStarting

No messages yet

Use the example above. Each message that reaches update shows here, with what it changed.