Skip to content

Instantly share code, notes, and snippets.

@aceakash
Created June 26, 2017 21:37
Show Gist options
  • Save aceakash/025b5681a960fc11ae8fab89b05294e6 to your computer and use it in GitHub Desktop.
Save aceakash/025b5681a960fc11ae8fab89b05294e6 to your computer and use it in GitHub Desktop.
Cat gif fetcher
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!" ]
]
@aceakash
Copy link
Author

Wanting to fetch a gif when the program started, I had to create foo (line 37 and 40) to call update.
Is there a better way? Feels a bit hacky...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment