|
| 1 | +module CatGifsReactHooks.Main where |
| 2 | + |
| 3 | +import Prelude |
| 4 | +import Affjax as Affjax |
| 5 | +import Affjax.ResponseFormat as ResponseFormat |
| 6 | +import Data.Argonaut.Decode (decodeJson) |
| 7 | +import Data.Argonaut.Decode.Combinators ((.:)) |
| 8 | +import Data.Either (hush) |
| 9 | +import Data.Maybe (Maybe(..), maybe) |
| 10 | +import Effect (Effect) |
| 11 | +import Effect.Aff (Aff) |
| 12 | +import Effect.Exception (throw) |
| 13 | +import React.Basic.DOM (css, render) |
| 14 | +import React.Basic.DOM as R |
| 15 | +import React.Basic.Events (handler_) |
| 16 | +import React.Basic.Hooks (Component, component, (/\)) |
| 17 | +import React.Basic.Hooks as React |
| 18 | +import React.Basic.Hooks.Aff (useAff) |
| 19 | +import React.Basic.Hooks.ResetToken (useResetToken) |
| 20 | +import Web.DOM.NonElementParentNode (getElementById) |
| 21 | +import Web.HTML (window) |
| 22 | +import Web.HTML.HTMLDocument (toNonElementParentNode) |
| 23 | +import Web.HTML.Window (document) |
| 24 | + |
| 25 | +data GifState |
| 26 | + = Failure |
| 27 | + | Loading |
| 28 | + | Success String |
| 29 | + |
| 30 | +main :: Effect Unit |
| 31 | +main = do |
| 32 | + container <- getElementById "root" =<< map toNonElementParentNode (document =<< window) |
| 33 | + case container of |
| 34 | + Nothing -> throw "Root element not found." |
| 35 | + Just c -> do |
| 36 | + catGifs <- mkCatGifs |
| 37 | + render (catGifs {}) c |
| 38 | + |
| 39 | +mkCatGifs :: Component {} |
| 40 | +mkCatGifs = do |
| 41 | + component "CatGifs" \_ -> React.do |
| 42 | + (resetToken /\ reset) <- useResetToken |
| 43 | + gifState <- toGifState <$> useAff resetToken getRandomCatGif |
| 44 | + let |
| 45 | + onClick = handler_ reset |
| 46 | + pure |
| 47 | + $ R.div_ |
| 48 | + [ R.h2_ [ R.text "Random Cats" ] |
| 49 | + , case gifState of |
| 50 | + Loading -> R.text "Loading..." |
| 51 | + Failure -> |
| 52 | + R.div_ |
| 53 | + [ R.text "I could not load a random cat for some reason. " |
| 54 | + , R.button { onClick, children: [ R.text "Try Again!" ] } |
| 55 | + ] |
| 56 | + Success url -> |
| 57 | + R.div_ |
| 58 | + [ R.button { onClick, style: css { display: "block" }, children: [ R.text "More Please!" ] } |
| 59 | + , R.img { src: url } |
| 60 | + ] |
| 61 | + ] |
| 62 | + |
| 63 | +-- | Collapse nested `Maybe`s to our `GifState` type |
| 64 | +toGifState :: Maybe (Maybe String) -> GifState |
| 65 | +toGifState = maybe Loading (maybe Failure Success) |
| 66 | + |
| 67 | +getRandomCatGif :: Aff (Maybe String) |
| 68 | +getRandomCatGif = do |
| 69 | + response <- |
| 70 | + Affjax.get |
| 71 | + ResponseFormat.json |
| 72 | + "https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cat" |
| 73 | + pure do |
| 74 | + -- Using `hush` to ignore the possible error messages |
| 75 | + { body } <- hush response |
| 76 | + hush (decodeJson body >>= (_ .: "data") >>= (_ .: "image_url")) |
0 commit comments