This article is intended for people who are already familiar with the MVU architecture. You can learn more about it on the Elmish website.
I am one of the maintainers of Elmish and I created several Fable / Elmish libraries and applications. When doing so, I needed to understand Elmish deeply and I want to take the opportunity of the F# Advent Calendar to share with you my tips and knowledge.
I will be covering a lot in this article, so grab yourself a cup of tea 🍵, take a deep breath 💨 and let’s get started 🏁.
Commands
A command is a container for a function that Elmish executes immediately, but which may schedule the dispatch of a message at any time.
For example:
- Issue a new Message immediately
- Make an HTTP call and then return the result in your application via a Message
- Save data in your storage
Basic usage
In this section, I will cover all the default functions offered by Elmish and show an example of each.
Use Cmd.none to schedule no Commands.
type Model =
{ Tick : int }
type Msg =
| Tick
let private update msg model =
match msg with
| Tick ->
{ model with Tick = model.Tick + 1 }, Cmd.none
Use Cmd.ofMsg to schedule another message directly, it can be seen as a way to chain messages.
type Model =
{ Value : string }
type Msg =
| ChangeValue of string
| ValidateData
let private update msg model =
match msg with
| ChangeValue newValue ->
{ model with Value = newValue }, Cmd.ofMsg ValidateData
Use Cmd.map to map a command to another type. In general, you use this function when working with nested components.
type Model =
{ Timeline : Timeline.Model }
type Msg =
| TimelineMsg of Timeline.Msg
let private update (msg : Msg) (model : Model) : Model * Cmd<Msg> =
match msg with
| TimelineMsg timelineMsg ->
let (timelineModel, timelineCmd) = Timeline.update timelineMsg model.Timeline
{ Timeline = timelineModel }, Cmd.map TimelineMsg timelineCmd
Use Cmd.ofAsync to evaluate an async block and map the result into success or error (of exception).
type Model =
{ InputValue : string
UpperValue : string }
type Msg =
| ToUpper of string
| OnUpperResult of string
| OnUpperError of exn
let private update (msg : Msg) (model : Model) =
match msg with
| ToUpper txt ->
let asyncUpper (txt : string) =
async {
do! Async.Sleep 1000
return txt.ToUpper()
}
model, Cmd.ofAsync asyncUpper txt OnUpperResult OnUpperError
| OnUpperResult result ->
{ model with UpperValue = result }, Cmd.none
| OnUpperError error ->
Browser.console.error error
model, Cmd.none
Use Cmd.ofFunc to evaluate a simple function and map the result into success or error (of exception).
type Model =
{ CurrentRoute : Route
Value : string
Tick : int
UpperValue : string }
type Msg =
| Save of string
| OnSaveSuccess of bool
| OnSaveError of exn
let private update (msg : Msg) (model : Model) =
match msg with
| Save txt ->
let save (txt : string) =
// If there is an error, an exception will be thrown and captured by Cmd.ofFunc
Browser.localStorage.setItem("my-app.input", txt)
true
model, Cmd.ofFunc save txt OnSaveSuccess OnSaveError
| OnSaveSuccess result ->
// Here we can notify the user that the save succeeded
model, Cmd.none
| OnSaveError error ->
// Here we can notifu the user that the save failed
Browser.console.error error
model, Cmd.none
Use Cmd.performFunc to evaluate a simple function and map the success to a message discarding any possible error.
type Model =
{ IsLoading : bool
Value : string }
type Msg =
| Load
| OnLoadSuccess of bool
let private update (msg : Msg) (model : Model) =
match msg with
| Load ->
// This function can never fail so we can use Cmd.performFunc
let load () =
let storedValue : string = Browser.localStorage.getItem("my-app.input") :?> string
if isNull storedValue then
""
else
storedValue
{ model with IsLoading = true }, Cmd.performFunc load () OnLoadSuccess
| OnLoadSuccess value ->
{ model with IsLoading = false
Value = value }, Cmd.none
Use Cmd.attemptFunc to evaluate a simple function and map the error (in case of exception).
type Model =
{ Value : string }
type Msg =
| ChangeValue of string
| OnLogError of exn
let private update (msg : Msg) (model : Model) =
match msg with
| ChangeValue newValue ->
let log (msg : string) =
// Send a msg to your logger
// If there is an error it will throw
Log.send msg
let msg = sprintf "Value changed from %s to %s" model.Value newValue
{ model with Value = newValue }, Cmd.attemptFunc log msg OnLogError
| OnLogError value ->
// There was an error during logging, should we do something ?
model, Cmd.none
Use Cmd.ofPromise to call a promise block and map the results.
type Model =
{ Value : int }
type Msg =
| Submit
| OnPromiseSuccess of int
| OnPromiseError of exn
let private update (msg : Msg) (model : Model) =
match msg with
| Submit ->
let myPromise () =
promise {
do! Promise.sleep 1000
return 10
}
model, Cmd.ofPromise myPromise () OnPromiseSuccess OnPromiseError
| OnPromiseSuccess value ->
{ model with Value = value }, Cmd.none
| OnPromiseError error ->
Browser.console.error error
model, Cmd.none
Use Cmd.ofSub to call the subscriber. This is useful when you are dealing with an API which uses callbacks or to listen to an event.
type Model =
{ Position : Browser.Position option
ErrorMessage : string }
type Msg =
| GetPosition
| GetPositionSuccess of Browser.Position
| GetPositionError of Browser.PositionError
module Sub =
// Subscriber used to reach gealocation API
let getPosition onSuccess onError dispatch =
Browser.navigator.geolocation.getCurrentPosition(
onSuccess >> dispatch,
onError >> dispatch
)
let update (msg:Msg) (model:Model) =
match msg with
| GetPosition ->
model, Cmd.ofSub (Sub.getPosition GetPositionSuccess GetPositionError)
| GetPositionSuccess posision ->
{ model with Position = Some position
ErrorMessage = "" }, Cmd.none
| GetPositionError error ->
{ model with Position = None
ErrorMessage = error.message }, Cmd.none
Use Cmd.batch to aggregate multiple commands. You can aggregate any of the previous commands together.
type Model =
{ Data1 : int
Data2 : int }
type Msg =
| FetchDatas
| OnFetchData1 of int
| OnFetchData2 of int
| OnPromiseError of exn
| OnLogError of exn
let private update (msg : Msg) (model : Model) =
match msg with
| FetchDatas ->
model, Cmd.batch [ Cmd.ofPromise fetchData1 () OnFetchData1 OnPromiseError
Cmd.ofPromise fetchData2 () OnFetchData2 OnPromiseError
Cmd.performFunc log "FetchDatas message has been treated" OnLogError ]
| OnFetchData1 data1 ->
{ model with Data1 = data1 }, Cmd.performFunc log "FetchData1 data has been received" OnLogError
| OnFetchData2 data2 ->
{ model with Data2 = data2 }, Cmd.performFunc log "FetchData2 data has been received" OnLogError
| OnPromiseError error ->
Browser.console.error("An error occured when fetching data", error)
model, Cmd.none
| OnLogError error ->
Browser.console.error("An error occured when logging", error)
model, Cmd.none
The functions provided out of the box by Elmish are enough to cover most of the needs of your application. However, when working on a library or with a specific API you may want to create your own commands. We will take a look at it later.
Model your Model according to your needs
When working with a Single Page Application, you will have to deal with navigation and need to reflect it in your models.
In general, when I am working at a page level, I use a Discriminated Union so I can store only the active page state.
For example, if in your application you have a login page you can’t store your authenticated page state in your application because you can’t fetch the resource to display it.
In general my main Model looks like this:
[<RequireQualifiedAccess>]
type AuthPage =
// Section for the website related to Messages management
// For example
// - Display the list of Messages
// - Create a message
| Messages of Messages.Model
// Administration section of the website
| Administration of Administration.Model
[<RequireQualifiedAccess>]
type Page =
// The application is loading, display a loader
| Loading
// Login page
| Login of Login.Model
// From here, the user need to be authenticated
| AuthPage of AuthPage
// Global error page like:
// - Generic error
// - You need to be connected
| Errored of Errored.Reason
// A page that can be accessed when the user is not logged in
// For example, to reset it's password from an URL
| ResetAccount of ResetAccount.Model
type Model =
{ // Store the user session information
// If Some xxx, then the user is signed-in
// If None, the user isn't connected
Session : User option
// Store the active page state
ActivePage : Page
// Store the current route information, this is useful if your
// route have parameters than you need to pass to child later
CurrentRoute : Router.Route option }
Using DUs to represent your page state helps you isolate your logic. For me, the biggest benefit compared to storing all page states in a big record is that you are not caching your page when navigating.
Of course sometimes your application needs to maintain state between navigations. For example, if you have a form in several steps you could model it like this:
type Rank =
| One
| Two
type Step1 =
{ Login : string
Password : string }
type Step2 =
{ Age : int
Surname : string
Firstname : string }
type Model =
{ CurrentRank : Rank
Step1 : Step1
Step2 : Step2 }
let private view (model : Model) (dispatch : Msg -> unit) =
match model.CurrentRank with
| Rank.One -> // render step n°1 form
| Rank.Two -> // render step n°2 form
Everything is a function
One thing we tend to forget when working with Elmish is that everything is a function. The main reason for this forgetfulness is that most of the examples only show you this code:
type Model =
{ Value : int }
type Msg =
| SomeAction
let init =
{ Value = 0 }, Cmd.none
let update (msg : Msg) (model : Model) : Model * Cmd<Msg> =
match msg with
| SomeAction ->
model, Cmd.none
let view (model : Model) (dispatch : Msg -> unit) : React.ReactElement =
div [ ]
[ str "This is my view" ]
So in our mind update takes two arguments when in fact we should think update takes at least two arguments. The same applies to view and init functions.
This idea is linked to the fact that a component’s Model should have all the information needed by the component, but this is not always true.
Pass data as an argument
For example, if you have a session in your application in order to make HTTP calls, should you store this session in each component’s Model?
No, you should store it in one place and then pass your session to the functions that need it.
The next code illustrates this situation: we request a session argument in our init function because we need to make an authenticated HTTP request using Http.Auth.* (custom module used, includes the session info in a request).
open Elmish
open Fable.Import
open Fable.PowerPack
type Session =
{ Token : string
UserId : int }
type Model =
| Loading
| Loaded of string
| Errored
type Msg =
| OnFetchDataSuccess of string
| OnFetchDataError of exn
let private fetchData (session : Session) : JS.Promise<string> =
promise {
let! res = Http.Auth.postRecord "/api/get-data" session
return! res.text()
}
let init (session : Session) =
Loading, Cmd.ofPromise (fetchData session) OnFetchDataSuccess OnFetchDataError
let private update (msg : Msg) (model : Model) =
match msg with
| OnFetchDataSuccess value ->
Loaded value, Cmd.none
| OnFetchDataError error ->
Browser.console.error error
Errored, Cmd.none
Pass a record as an argument
If your view function takes several arguments you can use a record as an argument. It will force you to name the arguments and by doing so make your code easier to read and maintain over time.
type private SectionProps =
{ Icon : Fa.IconOption
Count : int
Label : string
IsActive : bool
ZoneColor : string }
let private renderSection (props : SectionProps) =
// Render the view
let view (model : Model) =
renderSection
{ Icon = Fa.Solid.Cog
Count = model.ZoneA.Value + model.ZoneB.Value
Label = model.Zone.Name
IsActive = model.IsActive
ZoneColor = findColor model.Zone.ColorIndex }
It will also make it easier to optimize your code for React using memoBuilder.
type private SectionProps =
{ Icon : Fa.IconOption
Count : int
Label : string
IsActive : bool
ZoneColor : string }
let private renderSection =
memoBuilder "Section" (fun (props : SectionProps) ->
// Render the view
)
let view (model : Model) =
renderSection
{ Icon = Fa.Solid.Cog
Count = model.ZoneA.Value + model.ZoneB.Value
Label = model.Zone.Name
IsActive = model.IsActive
ZoneColor = findColor model.Zone.ColorIndex }
Use helper functions to work with your Domain
For example, when an Elmish component needs to fetch data from the server often, I like to show a loading animation. Here is how I handle it:
type LoadedModel =
{ Data : Data }
type Model =
| Loading
| Errored
| Loaded of LoadedModel
let private applyIfLoaded model (func : LoadedModel -> LoadedModel * Cmd<Msg>) =
match model with
| Loaded loadedModel ->
let res = func loadedModel
Loaded (fst res), snd res
| Errored _
| Loading -> model, Cmd.none
let update (msg : Msg) (model : Model) : Model * Cmd<Msg> =
match msg with
| SomeMessage ->
applyIfLoaded
model
(fun loadedModel ->
// Apply your logic here
)
As you can see I use a DU to represent if the component is Loaded, Loading or in an Errored state. And in order to simplify my update function, I use the applyIfLoaded function. This helps me keep the update code simple and easy to read.
Make public the bare minimum
By default in F# everything is public, so you need to explicitly use the private keyword for your functions and types to restrict their access.
let init =
{ Value : int }, Cmd.none
let private getUserInfo (userId : int) =
// ...
let update (msg : Msg) (model : Model) =
// ...
let private renderHeader (model : Model) =
// ...
let private renderContent (model : Model) =
// ...
let private renderFooter (model : Model) =
// ...
let view (model : Model) (dispatch : Msg -> unit) =
div [ ]
[ renderHeader model
renderContent model
renderFooter model ]
As you can see, I am only exposing init, update and view functions to the parent. This will allow easier refactoring and easier usability for you or others because you can directly see what API is available.
Make the child communicate with the parent
In general, a child should be independent from its parent and shouldn’t send messages to it. However, this is sometimes needed, for example if you have a Login component, you want to be able to detect a successful login and save the session in your application.
Most people do it this way:
open Elmish
open Fable.Import
type Session =
{ Token : string
UserId : int }
module Login =
type Msg =
| Login
| LoginCompleted of Session
| LoginFailed of exn
let update (msg : Msg) (model : Model) =
match msg with
// ...
| LoginCompleted _ ->
failwith "Should be captured by the parent"
module Parent =
type Model =
{ Session : Session option
Login : Login.Model }
type Msg =
| LoginMsg of Login.Msg
let private update (msg : Msg) (model : Model) =
match msg with
| LoginMsg loginMsg ->
match loginMsg with
| Login.Msg.LoginCompleted session ->
{ model with Session = Some session }, Cmd.none
| loginMsg ->
let (loginModel, loginCmd) = Login.update loginMsg model.Login
{ model with Login = loginModel }, Cmd.map LoginMsg loginCmd
They use failwith in the child to make “sure” to remember to capture the LoginCompleted message in the parent as it will throw an exception if we don’t capture it.
However, there is a major problem: if you add another message to capture in Login.Msg, the compiler will not be able to help us because we are using a greedy pattern | loginMsg ->.
A good solution to this problem is to use what I call ExternalMsg.
open Elmish
open Fable.Import
type Session =
{ Token : string
UserId : int }
module Login =
type ExternalMsg =
| NoOp
| SignedIn of Session
type Msg =
| Login
| LoginCompleted of Session
| LoginFailed of exn
let update (msg : Msg) (model : Model) =
match msg with
// ...
| LoginCompleted session ->
model, Cmd.none, SignedIn session
module Parent =
type Model =
{ Session : Session option
Login : Login.Model }
type Msg =
| LoginMsg of Login.Msg
let private update (msg : Msg) (model : Model) =
match msg with
| LoginMsg loginMsg ->
let (loginModel, loginCmd, loginExtraMsg) = Login.update loginMsg model.Login
// Here we can match over loginExtraMsg to do something
let newModel =
match loginExtraMsg with
| Login.ExternalMsg.NoOp -> model
| Login.ExternalMsg.SignedIn session -> { model with Session = Some session }
{ newModel with Login = loginModel }, Cmd.map LoginMsg loginCmd
By making Login.update return Model * Cmd<Msg> * ExternalMsg we help the compiler guide us to the correct way of handling the data. It forces me to handle ExternalMsg in the parent. Also, if I add a new case it will generate a warning telling me where I need to handle the new case.
Schedule a parent message in a child component
When working on a library or abstraction layer it can be necessary to schedule a message coming from a parent in the child components.
For example, Thoth.Elmish.Debouncer (we will call it debouncer from now) uses this feature in order to debounce a message.
In order to do that the debouncer exposes two functions:
bounce, which works withCmd<Debouncer.Msg>update, which works withCmd<Parent.Msg>
If you want to see how this is implemented, you can take a look at the code, it’s only about 50 lines.
Use several views for the same component
Sometimes a component has the same features but different displays, but you still want to use it in several places in your application.
For example, in the next code we render the Switch.switch element in a different size depending on our needs.
let viewNormal (model : Model) (dispatch : Msg -> unit) : React.ReactElement =
Switch.switch [ Switch.Checked model.IsActive
Switch.OnChange (fun _ -> ToggleDomainState model.DomainId |> dispatch)
Switch.Disabled model.IsWaitingServerReply ]
[ ]
let viewMedium (model : Model) (dispatch : Msg -> unit) : React.ReactElement =
Switch.switch [ Switch.Size IsMedium
Switch.Checked model.IsActive
Switch.OnChange (fun _ -> ToggleDomainState model.DomainId |> dispatch)
Switch.Disabled model.IsWaitingServerReply ]
[ ]
Extend the Elmish API
Disclaimer
In this section, I will show you advanced Elmish usage. Before using it in your application or library, you need to weigh the pros and cons compared to using the standard feature set.
For example, if Cmd.ofSub works, you should always favor using Cmd.ofSub over creating a custom command.
Also, this is not intended to be a guide/tutorial on how to implement it, I just want to mention that this is possible.
Program composition
By using program composition, you can add a new behavior to any Elmish application. For example, you can make it support navigation via URL, render using React, attach a debugger, etc.
This is exactly what you do when wiring your Elmish application:
open Elmish
open Elmish.Debug
open Elmish.Browser.Navigation
open Elmish.Browser.UrlParser
open Elmish.React
// Create the initial program
Program.mkProgram init update view
// Make your program support navigation via URL / Adress bar
|> Program.toNavigable (parseHash Router.routeParser) setRoute
#if DEBUG
// Add redux debugger support
|> Program.withDebugger
#endif
// Make your program render using React
|> Program.withReact "elmish-app"
// Start your program
|> Program.run
Custom commands
It is also possible to create your own commands.
For example, Elmish.Browser offers several Navigation commands:
(**
#### Direct history manipulation
*)
[<RequireQualifiedAccess>]
module Navigation =
let [<Literal>] internal NavigatedEvent = "NavigatedEvent"
/// Modify current location
let modifyUrl (newUrl:string):Cmd<_> =
[fun _ -> history.replaceState((), "", newUrl)]
/// Push new location into history and navigate there
let newUrl (newUrl:string):Cmd<_> =
[fun _ -> history.pushState((), "", newUrl)
let ev = document.createEvent_CustomEvent()
ev.initCustomEvent (NavigatedEvent, true, true, obj())
window.dispatchEvent ev
|> ignore ]
/// Jump to some point in history (positve=forward, nagative=backward)
let jump (n:int):Cmd<_> =
[fun _ -> history.go n]
Refine your user experience
You can combine all the techniques I spoke about here to improve the user experience of Elmish.
For example, Thoth.Elmish.Toast is a library adding global notification support for any component in an Elmish application. It uses:
- Program composition to register the library logic and views
- Custom commands in order to send a notification to the program directly
- F# features to provide a
Toastbuilder interface using pipes
open Elmish
open Elmish.React
open Thoth.Elmish
// Create the initial program
Program.mkProgram init update view
// Make your program support global notification
|> Toast.Program.withToast Toast.render
// Make your program render using React
|> Program.withReact "elmish-app"
// Start your program
|> Program.run
// Then you can trigger a notification from any component
let update (msg : Msg) (model : Model) : Model * Cmd<Msg> =
match msg with
| DemoInfo ->
model, Toast.message "I am toast of type Info"
|> Toast.title "Info"
|> Toast.info
Conclusion
Elmish is a really powerful library and makes good use of the standard F# features like function composition, partial application, and guides you to write safe code (handling success and error cases).
It also offers you powerful customization if the standard features are not enough.
I hope you found this article useful and that it will help you.