Skip to content

Instantly share code, notes, and snippets.

@jmn
Forked from anonymous/Main.elm
Created October 3, 2017 12:16
Show Gist options
  • Save jmn/170cfeab05fa40cec72965d718bad191 to your computer and use it in GitHub Desktop.
Save jmn/170cfeab05fa40cec72965d718bad191 to your computer and use it in GitHub Desktop.
Untitled
{
"repository": "https://github.com/user/project.git",
"version": "1.0.0",
"elm-version": "0.18.0 <= v < 1.0.0",
"summary": "Tell the world about your project!",
"license": "BSD3",
"source-directories": [
"."
],
"exposed-modules": [],
"native-modules": false,
"dependencies": {
"elm-lang/core": "5.1.1 <= v < 6.0.0",
"elm-lang/html": "2.0.0 <= v < 3.0.0",
"elm-lang/http": "1.0.0 <= v < 2.0.0"
}
}
<html>
<head>
<style>
html {
background: #F7F7F7;
color: red;
}
</style>
</head>
<body>
<script>
var app = Elm.Main.fullscreen()
</script>
</body>
</html>
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode as Decode
main : Program Never Model Msg
main =
Html.program
{ init = init "cats"
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ topic : String
, gifUrl : String
, error : Maybe String
}
init : String -> (Model, Cmd Msg)
init topic =
( Model topic "waiting.gif" Nothing
, getRandomGif topic
)
-- 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 model.topic newUrl Nothing, Cmd.none)
NewGif (Err _) ->
( { model | error = Just "Something went wrong." }, Cmd.none)
-- VIEW
view : Model -> Html Msg
view model =
div []
[ h2 [] [text model.topic]
, button [ onClick MorePlease ] [ text "More Please!" ]
, br [] []
, case model.error of
Nothing ->
img [src model.gifUrl] []
Just error ->
div [ ] [ text error ]
]
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- HTTP
getRandomGif : String -> Cmd Msg
getRandomGif topic =
let
url =
"https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" ++ topic
in
Http.send NewGif (Http.get url decodeGifUrl)
decodeGifUrl : Decode.Decoder String
decodeGifUrl =
Decode.at ["data", "image_url"] Decode.string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment