Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Last active July 20, 2020 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save choonkeat/e4871df45fb15752059c4fc9d244ad25 to your computer and use it in GitHub Desktop.
Save choonkeat/e4871df45fb15752059c4fc9d244ad25 to your computer and use it in GitHub Desktop.
{-| Maybe like how data from remote server can be modelled with 4 states `krisajenkins/remotedata`
perhaps form input can be modelled similarly too, giving us a convenient way to work with them
`err` stores validation errors for the form values, e.g. Dict String String
`a` stores the raw value from user input, e.g. Dict String String
`b` is the data type that we expect to wield if `a` is valid, e.g. API.CreateUser.Input
-}
type FormData err a b
= NotValid a err
| Valid a b
| Submitted a b
{-| a standard helper function to get that raw values, e.g. for rendering as html
-}
raw : FormData err a b -> a
{-| a standard helper function to get that err values, e.g. for rendering error messages in form html
-}
err : FormData err a b -> Maybe err
{-| a standard helper function to move `Valid` to `Just (Submitted...)`
otherwise, return `Nothing` if it was `NotValid` or `Submitted`
-}
submit : FormData err a b -> Maybe (FormData err a b)
--- Main.elm
{-| A custom function for each form of the app
update raw value `a` to store the values as-is and values are valid to create a `b` then we should return `Valid a b`
-}
updateUserProfileForm : FormData err a b -> String -> String -> FormData err a b
updateUserProfileForm oldForm fieldName inputValue =
{-|
Our app's `view` can
1. enable buttons only for `Valid` variant
1. show `Processing...` when in the `Submitted` variant
1. each field can thus do something like `onInput (OnUpdateUserProfile "name")`
then our `update` can also be ...
-}
update msg model =
case msg of
OnUpdateUserProfile fieldName inputValue ->
let
newForm =
updateUserProfileForm model.form fieldName inputValue
in
({ model | form = newForm }, Cmd.none)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment