Last active
September 17, 2016 03:27
-
-
Save aotarola/62c8b4a067e8d0dcb40cca9e24133566 to your computer and use it in GitHub Desktop.
Trying to reset a `select` element to previous value (when a task fails)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (..) | |
import Html.App as App | |
import Html exposing (..) | |
import Html.Attributes exposing (..) | |
import Json.Decode as Json | |
import Html.Events exposing (on, targetValue) | |
import String | |
import Task | |
import Json.Decode as Decode exposing ((:=)) | |
-- Problem: | |
-- I want the user to select a value from a dropdown list, | |
-- I purposely made a Task to fail, so the selected value "resets" to `5`, problem is, | |
-- this doesn't always work, it is randomly saving the state of the selected | |
-- value in the DOM element | |
type alias Model = | |
Int | |
-- Shows the dropdown list with value 5 pre-selected at first | |
init : ( Model, Cmd Msg ) | |
init = | |
( 5, Cmd.none ) | |
type Msg | |
= ChangeQuantity Model | |
| OnSucceed | |
| OnFailure Model | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
ChangeQuantity n -> | |
( n, fetch model ) | |
OnSucceed -> | |
( model, Cmd.none ) | |
OnFailure oldValue -> | |
( oldValue, Cmd.none ) | |
view : Model -> Html Msg | |
view model = | |
let | |
getOptions x = | |
option [ value (toString x), selected (model == x) ] [ text (toString x) ] | |
in | |
select [ onChangeIntValue ChangeQuantity ] (List.map getOptions [1..10]) | |
onChangeIntValue : (Int -> a) -> Html.Attribute a | |
onChangeIntValue a = | |
let | |
targetValueIntDecoder = | |
targetValue | |
`Json.andThen` | |
\val -> | |
case String.toInt val of | |
Ok i -> | |
Json.succeed i | |
Err err -> | |
Json.fail err | |
in | |
on "change" (Json.map a targetValueIntDecoder) | |
fetch : Model -> Cmd Msg | |
fetch model = | |
(Task.fail model) |> Task.perform OnFailure (always OnSucceed) | |
main : Program Never | |
main = | |
App.program | |
{ init = init | |
, update = update | |
, view = view | |
, subscriptions = always Sub.none | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment