mfrachet
mfrachet

Reputation: 8932

Elm adding item in a list on update

I m trying to understand Elm lang, and I m having some problem dealing with the update part of my little app.

Actually, I want that when I click on a button, it adds a new User in a List, something really simple that doesn't have any sense, but I need to understand.

Right now, I m having the following code :

main =
  Html.beginnerProgram { model = model, view = view, update = update }

type Msg = AddUser
type alias User =
    {
        username : String,
        firstname: String,
        lastname: String
    }

model: List User
model =
    []

update: Msg -> User -> List User -> List User
update msg user userList =
    case msg of
        AddUser ->
            user::userList

And I m having the following error :

-- TYPE MISMATCH ------------------------------------------------------ main.elm

The argument to function `beginnerProgram` is causing a mismatch.

5|   Html.beginnerProgram { model = model, view = view, update = update }
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Function `beginnerProgram` is expecting the argument to be:

    { ..., update : Msg -> List User -> List User }

But it is:

    { ..., update : Msg -> User -> List User -> List User }

Hint: Problem in the `update` field. I always figure out field types in
alphabetical order. If a field seems fine, I assume it is "correct" in
subsequent checks. So the problem may actually be a weird interaction with
previous fields.

In fact what I m currently understanding from the update function is :

But I can't get the point where I am wrong in this situation.

Can you help me ?

Upvotes: 4

Views: 5125

Answers (1)

farmio
farmio

Reputation: 9623

Html.beginnerProgram expects the update function to be of type Msg-> Model -> Model (your Model is named "User" which is no problem). The User you want to add belongs to the "AddUser" union type.

type Msg = AddUser User

This means you pass the new User along with the Msg (so you can use different messages passing different things). To get the new User you can pattern match it in "case"

case msg of
    AddUser newUser ->
        newUser :: userList

Upvotes: 8

Related Questions