Last active
September 17, 2016 03:30
-
-
Save aotarola/dcc94c26d81b4093a10b92946fa624d0 to your computer and use it in GitHub Desktop.
[solution using Process.sleep] Trying to reset a `select` element to previous value (when a task fails) Raw
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 ((:=)) | |
import Process | |
-- Workaround: it looks like Elm it is being way to fast when diffing the DOM, | |
-- it finishes before the browser is done rendering the select element, | |
-- the workaroud for this is to add a small delay (50ms), to give enough time | |
-- to the browser to finish doing the rendering work | |
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 | |
| NoOp | |
| Delayed Model | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
Delayed n -> | |
( n, Cmd.none ) | |
NoOp -> | |
( model, Cmd.none ) | |
ChangeQuantity n -> | |
( n, fetch model ) | |
OnSucceed -> | |
( model, Cmd.none ) | |
OnFailure oldValue -> | |
model | |
! [ Process.sleep 50 | |
|> Task.perform (always NoOp) (always (Delayed oldValue)) | |
] | |
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