🌳
Walking though the Elm woods
  • Introduction
  • Structure of the book
  • Frequently asked questions
    • How can different types share data?
    • How to break Dependency Cycles?
    • How to structure an Elm project?
    • How to turn a Msg into a Cmd Msg?
    • How to update nested Records?
    • What are comparable types?
    • Why are Booleans bad?
    • 🔜Future topics
  • Recipes
    • Writing a Single Page Application
      • Share state across pages
      • Debounced Validation
      • Reusable views
    • Making impossible states Impossible
      • Non empty lists using Zippers
      • Restrict records using Opaque Types
      • Write safer functions using Phantom Types
    • Designing Elm package APIs
      • Create upwards compatible APIs
    • 🔜Future topics
  • Frameworks and packages
    • elm/parser
    • mdgriffith/elm-ui
    • 🔜Future topics
Powered by GitBook
On this page
  • Question
  • Answer
  • Further reading

Was this helpful?

  1. Frequently asked questions

How to turn a Msg into a Cmd Msg?

Only Use Sparsely: Better split the update function into multiple smaller functions.

type Msg =
  LoginSucceeded User
  | InfoMessage String
  
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    LoginSucceeded newUser ->
      ( { model | currentUser = newUser }
      , Cmd.none
      )
    InfoMessage message ->
      ( { model | message = Just message }
      , Cmd.none
      )
type Msg =
  LoginSucceeded User
  | InfoMessage String
  
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    LoginSucceeded newUser ->
      ( { model | currentUser = newUser }
      , sendMsg <| InfoMessage "Login Successful"
      )
    InfoMessage message ->
      ( { model | message = Just message }
      , Cmd.none
      )

sendMsg : msg -> Cmd msg
sendMsg msg =
  Task.succeed msg
  |> Task.perform identity
type Msg =
  LoginSucceeded User
  | InfoMessage String
  
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    LoginSucceeded newUser ->
      ( model
        |> updateUser newUser
        |> updateMessage "Login Successful"
      , Cmd.none
      )
    InfoMessage message ->
      ( model |> updateMessage message
      , Cmd.none
      )

updateUser : User -> Model -> Model
updateUser user model =
  { model | currentUser = user }

updateMessage : String -> Model -> Model
updateMessage message model =
  { model | message = Just message }

This is the a better solution

Question

How can I display a Message after a user logged in?

Answer

Use the following function:

sendMsg : msg -> Cmd msg
sendMsg msg =
  Task.succeed msg
  |> Task.perform identity

Further reading

PreviousHow to structure an Elm project?NextHow to update nested Records?

Last updated 5 years ago

Was this helpful?

📄Article: by Wouter In t Velt

How to turn a Msg into a Cmd Msg in Elm?