Let’s get one thing straight: building real-world single page applications which sync information with a server is hard.

Mithril’s m.request() method has a ton of options and I won’t duplicate the explanation you can find in the official documentation. We’re just going to pretend servers never fail and connections never time out in Middle-earth.

"And you are lucky to be here too after all the absurd things you’ve done since you left home." - Gandalf

In this example, we’ll load data from an actual server (mine) and display it.

Click on the Load Fellowship button and after a brief delay (2+ seconds), the button should be replaced with a paragraph of text describing the Fellowship.

There are three things I’d like to point out in this example.

First, the get_fellowship() function contains the call to m.request() which is of primary interest. Note that it takes an options parameter in which you set the options for your request. In this case, we set the method and url.

Second, note the .then() which follows the m.request() call. The request returns a promise object, which contains a then() method. We use the promise to tell Mithril what to do after the request is done (and do something with the result). In this case, we’re using our getter/setter prop called Fellowship.data to store whatever comes back from the request.

Finally, make note of the view_fellowship() function. In place of large trinary conditions in the view() , it can be much cleaner to make auxilary view functions which contain this logic. You can chain together any number of function calls to render your view. Mithril is infinitely flexible.

Oh yeah, and how did Mithril know to update the display after the data was loaded? Just as with the events we’ve been using above, Mithril also redraws after a call to m.request() is complete. And as always, the display updates because a value changed and we displayed it differently from our view.

This example did its job with minimal code, but it was hard to tell that anything was happening after you pressed the button. Let’s add a "Loading…​" notification to the example. While we’re at it, let’s display something more interesting than the paragraph of text.

Instead of thinking of this as a component that:

Displays a "Loading…​" message when you click on a button

Then makes it disappear

Then displays a table of data

Think of it as a component with:

A variable called loading that might contain a message

A view_table() function that returns null or a table

Being able to think of your view in terms of little discrete bits of state rather than a series of actions is one of the ways Mithril helps make applications easier to contain in your mind.