Skip to content

Instantly share code, notes, and snippets.

@selbekk
Created January 2, 2020 22:47
Show Gist options
  • Save selbekk/2a9992378f646624818a4fc0cc51443b to your computer and use it in GitHub Desktop.
Save selbekk/2a9992378f646624818a4fc0cc51443b to your computer and use it in GitHub Desktop.
Dad joke app in Elm
module Main exposing (..)
import Browser
import Html exposing (..)
import Html.Attributes as A
import Html.Events as Events
import Http
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
-- COMMANDS
fetchDadJoke : Cmd Msg
fetchDadJoke =
Http.request
{ method = "GET"
, body = Http.emptyBody
, headers = [ Http.header "Accept" "text/plain" ]
, url = "https://icanhazdadjoke.com"
, expect = Http.expectString GotJoke
, timeout = Nothing
, tracker = Nothing
}
-- MODEL
type Model
= Failure
| Loading
| Success String
init : () -> ( Model, Cmd Msg )
init _ =
( Loading
, fetchDadJoke
)
-- UPDATE
type Msg
= GotJoke (Result Http.Error String)
| RequestNewJoke
update : Msg -> Model -> ( Model, Cmd Msg )
update msg _ =
case msg of
GotJoke result ->
case result of
Ok text ->
( Success text, Cmd.none )
Err _ ->
( Failure, Cmd.none )
RequestNewJoke ->
( Loading, fetchDadJoke )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
div [ A.style "text-align" "center" ]
[ h1 [] [ text "Elm dad jokes 😎" ]
, case model of
Loading ->
p [] [ text "Loading..." ]
Failure ->
div []
[ p [ A.style "color" "red" ]
[ text "Ouch, something went wrong while fetching the stuff over the network"
]
, button [ Events.onClick RequestNewJoke, A.type_ "button" ]
[ text "Try again" ]
]
Success theText ->
div []
[ pre [] [ text theText ]
, button [ Events.onClick RequestNewJoke, A.type_ "button" ]
[ text "Get another joke" ]
]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment