Noob question: Models getting wiped in between pushUrl calls

What the title says, I’m writing an SPA with Browser.application (basically just the frontend rn, don’t judge me lol). I have buttons like this:

button [ onClick SubmitInfo ] [ text "Submit" ]

where SubmitInfo is a Msg variant (incidentally, it’s not really clear to me how the Msg type matches the interface described by onClick).

Here’s the relevant update code:

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    SubmitInfo ->
      submitInfo model

And finally:

pushUrl : Model -> String -> ( Model, Cmd Msg )
pushUrl model url =
    ( model, Nav.pushUrl model.key url )

submitInfo : Model -> ( Model, Cmd Msg )
submitInfo model =
    pushUrl { model | loginStatus = LoggedIn } (Url.Builder.absolute [ "agreement" ] [])

Every time I push a button like this, the page loads correctly but the Model is empty again, as if the HTML has loaded from scratch again.

1 Like

Hi! Is your button inside a <form> element by any chance? If so, you are experiencing how forms work by default in browsers. Buttons have a type attribute and it defaults to "submit", which submits the form its in, which results in a full page reload. You can solve it by adding Html.Attributes.type_ "button".

5 Likes

Oh goodness. I don’t do much frontend work, so I’m embarrassed to say I’ve forgotten this behavior of <form> and <button> and gotten stuck on this bug a couple times before lol. Thanks for the pointer, that did the trick. Go Elm!

5 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.