Created
January 1, 2019 22:52
-
-
Save darkslategrey/ddbaba65be09ff77c58b529f31973b2e to your computer and use it in GitHub Desktop.
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 Cat exposing (Model(..), Msg(..), getRandomCatGif, gifDecoder, init, main, subscriptions, update, view, viewGif) | |
import Browser | |
import Html exposing (..) | |
import Html.Attributes exposing (..) | |
import Html.Events exposing (..) | |
import Http | |
import Json.Decode exposing (Decoder, field, string) | |
-- MAIN | |
main = | |
Browser.element | |
{ init = init | |
, update = update | |
, subscriptions = subscriptions | |
, view = view | |
} | |
-- MODEL | |
type Model | |
= Failure | |
| Loading | |
| Success String | |
init : () -> ( Model, Cmd Msg ) | |
init _ = | |
( Loading, getRandomCatGif ) | |
-- UPDATE | |
type Msg | |
= MorePlease | |
| GotGif (Result Http.Error String) | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
MorePlease -> | |
( Loading, getRandomCatGif ) | |
GotGif result -> | |
case result of | |
Ok url -> | |
( Success url, Cmd.none ) | |
Err _ -> | |
( Failure, Cmd.none ) | |
-- SUBSCRIPTIONS | |
subscriptions : Model -> Sub Msg | |
subscriptions model = | |
Sub.none | |
-- VIEW | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ h2 [] [ text "Random Cats" ] | |
, viewGif model | |
] | |
viewGif : Model -> Html Msg | |
viewGif model = | |
case model of | |
Failure -> | |
div [] | |
[ text "I could not load a random cat for some reason. " | |
, button [ onClick MorePlease ] [ text "Try Again!" ] | |
] | |
Loading -> | |
text "Loading..." | |
Success url -> | |
div [] | |
[ button [ onClick MorePlease, style "display" "block" ] [ text "More Please!" ] | |
, img [ src url ] [] | |
] | |
-- HTTP | |
getRandomCatGif : Cmd Msg | |
getRandomCatGif = | |
Http.get | |
{ url = "https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cat" | |
, expect = Http.expectJson GotGif gifDecoder | |
} | |
gifDecoder : Decoder String | |
gifDecoder = | |
field "data" (field "image_url" string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment