Commands are one of the essential features of an ELM architecture. They allow the application to interact with other components, such as servers. With commands, we can make HTTP requests, save something on local storage, generate random numbers, and so on.
Let's consider a scenario of serving user requests. To do this, the application needs to interact with other components, like micro-service, API, external server, and so on. This can only be achieved in ELM using commands.
The message is also a key component in ELM architecture, using which the users can interact with the application. End users interact with the application using messages, while commands enable the application to interact with other entities. In simple words, commands are triggered in response to a message.
Users can only interact with the view provided by the application. Based on the user input, different messages are displayed. When a user submits a request to update a component, the application receives it as a message and activates a command in response.
The following figure shows the workflow of any ELM application:
The following is the syntax for defining a command:
type Cmd message
The message
generated by the user to the application is passed to the command. Here, in this syntax, type
is a keyword, Cmd
is used to differentiate between different types of commands, and message
is what the command sends to the server.
Check the following example to understand the syntax of the ELM command better. In this example, a request is sent to the API and the result from the API is displayed. The syntax of the command for doing this is as follows:
type alias Model =
{ heading : String
, factText : String
, input :String
}
Free Resources