I’m building my first Elm-app, and struggle a little with how I should handle updates when I need a generated identifier for one of my types.
I have a module Label with a record type alias Label. The record contains a field of type LabelId which is a guarded Int. I also have a function to generate a new Label with some defaults. Currently it takes a LabelId and returns a tuple with the next LabelId and the new Label.
type alias Label =
{ id : LabelId, [...] }
type LabelId
= LabelId Int
create : LabelId -> (LabelId, Label)
create id = ...
In the model I keep a List of Labels and the next LabelId:
type alias Model =
{ nextLabelId : Label.LabelId
, labels : List Label.Label
}
Now in update, when I need a new Label, I could call Label.create model.nextLabelId
directly, but then I must always remember to store the returned LabelId in the model. Or I could wrap Label.create
with a function in Main:
createLabel : Model -> (Model, Label)
createLabel model =
let
( nextNextId, label ) =
Label.create model.nextLabelId
in
( { model | nextLabelId = nextNextId }, label )
I still have to remember to use the wrapper and to use the returned model in the result of the update function, but my gut feeling is that it is slightly less risky than the first approach.
What would be a best practice for handling this? Maybe I’m making things over complicated and there is a much better approach.