2

My app gets init model values from localstorage through flags. I added a new key to the model and it causes an error while starting the Elm app because of the missing key ("bar") in the value passed through flags. Considering that more new keys can be added in the future, and I don't want to have to clear localstorage every time it happens, is there a way to tell Elm to assign a default value when there is a missing key in the flag?

type alias Model =
    { foo : String, bar : Int }

update : msg -> Model -> ( Model, Cmd msg )
update _ model =
    model ! []

view : Model -> Html msg
view model =
    text <| toString model

main : Program Flags Model msg
main =
    Html.programWithFlags
        { init = init
        , update = update
        , view = view
        , subscriptions = always Sub.none
        }

HTML code

<body>
  <script>
    var app = Elm.Main.fullscreen({foo: "abc"})
  </script>
</body>
Jason O.
  • 3,168
  • 6
  • 33
  • 72

1 Answers1

7

Here is a great solution that @ilias at the Elm Slack channel kindly provided.

https://ellie-app.com/mWrNyQWYBa1/0

module Main exposing (main)

import Html exposing (Html, text)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Extra as Decode  --"elm-community/json-extra"


type alias Model =
    { foo : String, bar : Int }


flagsDecoder : Decoder Model
flagsDecoder =
    Decode.map2 Model
        (Decode.field "foo" Decode.string |> Decode.withDefault "hello")
        (Decode.field "bar" Decode.int |> Decode.withDefault 12)


init : Decode.Value -> ( Model, Cmd msg )
init flags =
    case Decode.decodeValue flagsDecoder flags of
        Err _ ->
            Debug.crash "gracefully handle complete failure"

        Ok model ->
            ( model, Cmd.none )


update : msg -> Model -> ( Model, Cmd msg )
update _ model =
    model ! []


view : Model -> Html msg
view model =
    text <| toString model


main : Program Decode.Value Model msg
main =
    Html.programWithFlags
        { init = init
        , update = update
        , view = view
        , subscriptions = always Sub.none
        }

HTML

<body>
  <script>
    var app = Elm.Main.fullscreen({foo: "abc"})
  </script>
</body>
Jason O.
  • 3,168
  • 6
  • 33
  • 72