Created
January 5, 2017 00:32
-
-
Save QuinnWilton/1d49d411274799b26de2c5319f68c92e to your computer and use it in GitHub Desktop.
Daily Drip [Elm 006.1] ported to Elm 0.18.0
This file contains hidden or 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 exposing (..) | |
import Html.Events exposing (onClick) | |
import Html.Attributes exposing (src) | |
import Json.Decode | |
import Http | |
import Task | |
import Json.Decode.Pipeline exposing (decode, required) | |
apiEndpoint : String | |
apiEndpoint = | |
"https://api.chucknorris.io/jokes/random" | |
type alias Model = | |
{ icon_url : String | |
, id : String | |
, value : String | |
} | |
type Msg | |
= FetchJoke | |
| ReceiveJoke (Result Http.Error Model) | |
initialModel : Model | |
initialModel = | |
{ icon_url = "" | |
, id = "" | |
, value = "" | |
} | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
FetchJoke -> | |
( model | |
, fetchJoke | |
) | |
ReceiveJoke (Ok joke) -> | |
( joke | |
, Cmd.none | |
) | |
ReceiveJoke (Err _) -> | |
( model | |
, Cmd.none | |
) | |
fetchJoke : Cmd Msg | |
fetchJoke = | |
Http.send ReceiveJoke (Http.get apiEndpoint jokeDecoder) | |
jokeDecoder : Json.Decode.Decoder Model | |
jokeDecoder = | |
decode Model | |
|> required "icon_url" Json.Decode.string | |
|> required "id" Json.Decode.string | |
|> required "value" Json.Decode.string | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ h3 [] [ text "Chuck Norris Jokes" ] | |
, viewJoke model | |
, button [ onClick FetchJoke ] [ text "Fetch a new joke" ] | |
] | |
viewJoke : Model -> Html Msg | |
viewJoke model = | |
div [] | |
[ img [ src model.icon_url ] [] | |
, p [] [ text model.value ] | |
] | |
main = | |
program | |
{ init = ( initialModel, Cmd.none ) | |
, update = update | |
, view = view | |
, subscriptions = subscriptions | |
} | |
subscriptions model = | |
Sub.none |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment