HTTP
For example, say we want to load the full text of Public Opinion by Walter Lippmann. Published in 1922, this book provides a historical perspective on the rise of mass media and its implications for democracy. For our purposes here, we will focus on how to use the elm/http
package to get this book into our program!
Click the blue “Edit” button to look through this program in the online editor. You will probably see the screen say “Loading…” before the full book shows up. Click the blue button now!
Some parts of this should be familiar from previous examples of The Elm Architecture. We still have a Model
of our application. We still have an update
that reacts to messages. We still have a view
function that shows everything on screen.
The new parts extend the core pattern we saw before with some changes in init
and update
, and the addition of subscription
.
The init
function describes how to initialize our program:
Our book website starts in the Loading
state, and we want to GET the full text of our book. When making a GET request with Http.get
, we specify the url
of the data we want to fetch, and we specify what we expect
that data to be. So in our case, the url
is pointing at some data on the Elm website, and we expect
it to be a big String
we can show on screen.
The Http.expectString GotText
line is saying a bit more than that we expect
a String
though. It is also saying that when we get a response, it should be turned into a GotText
message:
Notice that we are using the Result
type from a couple sections back. This allows us to fully account for the possible failures in our update
function. Speaking of functions…
Our update
function is returning a bit more information as well:
Looking at the type signature, we see that we are not just returning an updated model. We are also producing a command of what we want Elm to do.
So in the case that we got the full text successfully, we say Cmd.none
to indicate that there is no more work to do. We already got the full text!
And in the case that there was some error, we also say Cmd.none
and just give up. The text of the book did not load. If we wanted to get fancier, we could pattern match on the and retry the request if we got a timeout or something.
The point here is that however we decide to update our model, we are also free to issue new commands. I need more data! I want a random number! Etc.
The other new thing in this program is the subscription
function. It lets you look at the Model
and decide if you want to subscribe to certain information. In our example, we say Sub.none
to indicate that we do not need to subscribe to anything, but we will soon see an example of a clock where we want to subscribe to the current time!
When we create a program with Browser.element
, we set up a system like this: