Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. -- Read more about this program in the official Elm guide:
  2. -- https://guide.elm-lang.org/architecture/effects/http.html
  3.  
  4. import Html exposing (..)
  5. import Html.Attributes exposing (..)
  6. import Html.Events exposing (..)
  7. import Http
  8. import Json.Decode as Decode
  9.  
  10.  
  11.  
  12. main =
  13. Html.program
  14. { init = init "cats"
  15. , view = view
  16. , update = update
  17. , subscriptions = subscriptions
  18. }
  19.  
  20.  
  21.  
  22. -- MODEL
  23.  
  24.  
  25. type alias Model =
  26. { topic : String
  27. , gifUrl : String
  28. }
  29.  
  30.  
  31. init : String -> (Model, Cmd Msg)
  32. init topic =
  33. ( Model topic "waiting.gif"
  34. , getRandomGif topic
  35. )
  36.  
  37.  
  38.  
  39. -- UPDATE
  40.  
  41.  
  42. type Msg
  43. = MorePlease
  44. | NewGif (Result Http.Error String)
  45.  
  46.  
  47. update : Msg -> Model -> (Model, Cmd Msg)
  48. update msg model =
  49. case msg of
  50. MorePlease ->
  51. (model, getRandomGif model.topic)
  52.  
  53. NewGif (Ok newUrl) ->
  54. (Model model.topic newUrl, Cmd.none)
  55.  
  56. NewGif (Err _) ->
  57. (model, Cmd.none)
  58.  
  59.  
  60.  
  61. -- VIEW
  62.  
  63.  
  64. view : Model -> Html Msg
  65. view model =
  66. div []
  67. [ h2 [] [text model.topic]
  68. , button [ onClick MorePlease ] [ text "More Please!" ]
  69. , br [] []
  70. , img [src model.gifUrl] []
  71. ]
  72.  
  73.  
  74.  
  75. -- SUBSCRIPTIONS
  76.  
  77.  
  78. subscriptions : Model -> Sub Msg
  79. subscriptions model =
  80. Sub.none
  81.  
  82.  
  83.  
  84. -- HTTP
  85.  
  86.  
  87. getRandomGif : String -> Cmd Msg
  88. getRandomGif topic =
  89. let
  90. url =
  91. "https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" ++ topic
  92. in
  93. Http.send NewGif (Http.get url decodeGifUrl)
  94.  
  95.  
  96. decodeGifUrl : Decode.Decoder String
  97. decodeGifUrl =
  98. Decode.at ["data", "image_url"] Decode.string
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement