Created
June 26, 2017 21:37
-
-
Save aceakash/025b5681a960fc11ae8fab89b05294e6 to your computer and use it in GitHub Desktop.
Cat gif fetcher
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 (Html, button, div, h1, h2, img, text) | |
import Html.Attributes exposing (src) | |
import Html.Events exposing (onClick) | |
import Http exposing (Error, get) | |
import Json.Decode exposing (Decoder, at) | |
main : Program Never Model Msg | |
main = | |
Html.program | |
{ init = init | |
, view = view | |
, update = update | |
, subscriptions = \x -> Sub.none | |
} | |
-- MODEL | |
type alias Model = | |
{ topic : String | |
, gifUrl : String | |
} | |
initialModel : Model | |
initialModel = | |
Model "cats" "waiting.gif" | |
init : ( Model, Cmd Msg ) | |
init = | |
( initialModel, foo ) | |
foo : Cmd Msg | |
foo = | |
let | |
( _, cmd ) = | |
update MorePlease initialModel | |
in | |
cmd | |
-- UPDATE | |
type Msg | |
= MorePlease | |
| NewGif (Result Http.Error String) | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
MorePlease -> | |
( model, getRandomGif model.topic ) | |
NewGif (Ok newUrl) -> | |
( { model | gifUrl = newUrl }, Cmd.none ) | |
NewGif (Err _) -> | |
( model, Cmd.none ) | |
getRandomGif : String -> Cmd Msg | |
getRandomGif topic = | |
let | |
url = | |
"https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" ++ topic | |
request = | |
Http.get url decodeGifUrl | |
in | |
Http.send NewGif request | |
decodeGifUrl : Json.Decode.Decoder String | |
decodeGifUrl = | |
Json.Decode.at [ "data", "image_url" ] Json.Decode.string | |
-- VIEW | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ h2 [] [ text model.topic ] | |
, img [ src model.gifUrl ] [] | |
, button [ onClick MorePlease ] [ text "More Please!" ] | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wanting to fetch a gif when the program started, I had to create
foo
(line 37 and 40) to callupdate
.Is there a better way? Feels a bit hacky...