Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@stormont
Created November 28, 2016 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stormont/cb9af683cb5192ce7690b28c3feeddb2 to your computer and use it in GitHub Desktop.
Save stormont/cb9af683cb5192ce7690b28c3feeddb2 to your computer and use it in GitHub Desktop.
-- Read more about this program in the official Elm guide:
-- https://guide.elm-lang.org/architecture/effects/http.html
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode as Decode
main =
Html.program
{ init = init "cats"
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ topic : String
, gifUrl : String
}
init : String -> (Model, Cmd Msg)
init topic =
( Model topic "waiting.gif"
, 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, Cmd.none)
NewGif (Err e) ->
(Model model.topic (toString e), Cmd.none)
-- VIEW
view : Model -> Html Msg
view model =
div []
[ h2 [] [text model.topic]
, button [ onClick MorePlease ] [ text "More Please!" ]
, br [] []
, div [] [text model.gifUrl]
]
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- HTTP
getRandomGif : String -> Cmd Msg
getRandomGif topic =
let
url =
"https://www.elm-lang.org" -- Anything I put here will return "NetworkError"
in
Http.send NewGif (Http.getString url) -- (Http.get url decodeGifUrl) -- getString and Json decoding both return the same error
decodeGifUrl : Decode.Decoder String
decodeGifUrl =
Decode.at ["first_field"] Decode.string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment