Skip to content

Instantly share code, notes, and snippets.

@VictorBezak
Last active February 8, 2020 22:10
Show Gist options
  • Save VictorBezak/7c07938bf810ece085022eabc21459d4 to your computer and use it in GitHub Desktop.
Save VictorBezak/7c07938bf810ece085022eabc21459d4 to your computer and use it in GitHub Desktop.
Simplest example of a nested record update. Only one layer deep, and one way to update.
module Main exposing (..)
import Html exposing (Html, div, section, button, text)
import Html.Attributes exposing ()
import Html.Events exposing (onClick)
import Browser exposing (sandbox)
-- Type Schemas
type alias NestedRecord =
{ name : String, timesClicked : Int }
type alias Model =
{ person : NestedRecord }
-- Model Initialization
init : Model
init =
{ person = { name = "Iam You", timesClicked = 0 } }
-- VIEW
view : Model -> Html Msg
view model =
div []
[ section [] [ text ("My name is " ++ model.person.name) ]
, section [] [ text ("You've clicked me " ++ String.fromInt model.person.timesClicked ++ " times") ]
, button [ onClick Click ] [ text "Click Me" ]
]
-- UPDATE
type Msg
= Click
update : Msg -> Model -> Model
update msg model =
case msg of
Click ->
model
|> updateNestedValue
-- Helper functions to update our nested record
updateModel : (NestedRecord -> NestedRecord) -> Model -> Model
updateModel updateFunction model =
{ model | person = updateFunction model.person }
setNestedValue : NestedRecord -> NestedRecord
setNestedValue nestedRecord =
{ nestedRecord | timesClicked = nestedRecord.timesClicked + 1 }
updateNestedValue : Model -> Model
updateNestedValue =
updateModel <| setNestedValue
main : Program () Model Msg
main =
Browser.sandbox
{ init = init
, view = view
, update = update
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment