Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Daily Drip [Elm 006.1] ported to Elm 0.18.0
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