Created
January 2, 2020 22:47
-
-
Save selbekk/2a9992378f646624818a4fc0cc51443b to your computer and use it in GitHub Desktop.
Dad joke app in Elm
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 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