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
-- 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