Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dom not re-rendering on Model change (Elm)

Tags:

elm

I'm trying a simple Elm CRUD example, but the DOM is not re-rendering when I add a new item to a list of items in the model.

Right now, I'm just adding a static record, and I can confirm that the model is changing via the elm-reactor debugger, but the mapped itemView items is not updating w/ a new div element.

I feel like I might be missing a pretty important part of the Elm architecture/virtual dom. Can anybody point me in right direction?

import Html exposing (Html, text, beginnerProgram, div, input, button)
import Html.Events exposing (onInput, onClick)
import List exposing (map, repeat, append)

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

type alias Model =
    { items : List Item
    , inputTxt : String }

model : Model
model =
    { items = items
    , inputTxt = inputTxt }

type alias Item =
    { id : Int
    , txt : String }


item : Item
item =
    { id = 0
    , txt = "some text" }

items : List Item
items =
    repeat 2 item

inputTxt : String
inputTxt =
    ""

type Msg
    = NoOp
    | ChangeTxt String
    | AddItem


update : Msg -> Model -> Model
update msg model =
    case msg of
        NoOp ->
            model
        ChangeTxt newTxt ->
            { model | inputTxt = newTxt }
        AddItem ->
            { model | items = model.items ++ [{ id = 0, txt = "some text" }] }

view : Model -> Html Msg
view model =
    div [] [
        div [] [ itemsView items ]
        , div [] [
            input [ onInput ChangeTxt ] []
        ]
        , div [] [
            text model.inputTxt
        ]
        , div [] [
            button [ onClick AddItem ] [ text "click me!" ]
        ]
    ]

itemView : Item -> Html Msg
itemView item =
    div [] [
        div [] [ text ( toString item.id ) ]
        , div [] [ text item.txt ]
    ]

itemsView : List Item -> Html Msg
itemsView items =
    div [] [
        div [] (List.map itemView items)
    ]
like image 552
cannadayr Avatar asked Feb 07 '17 23:02

cannadayr


1 Answers

The second line of your view function should be

div [] [ itemsView model.items ]

Right now it always renders items defined above, not the items in the model.

like image 64
robertjlooby Avatar answered Oct 31 '22 13:10

robertjlooby