Created
October 9, 2020 12:57
-
-
Save pete-murphy/45aa8457f6534c7ca920c05f50428940 to your computer and use it in GitHub Desktop.
Example of useEffect, useAff in simple React app
This file contains hidden or 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
module Main where | |
import Prelude | |
import Data.Maybe (Maybe(..)) | |
import Effect (Effect) | |
import Effect.Class (liftEffect) | |
import Effect.Class.Console (log) | |
import Effect.Exception (throw) | |
import React.Basic.DOM (render) | |
import React.Basic.DOM as R | |
import React.Basic.Events (handler_) | |
import React.Basic.Hooks (Component, component, useEffect, useState, (/\)) | |
import React.Basic.Hooks.Aff (useAff) | |
import React.Basic.Hooks as React | |
import Web.HTML (window) | |
import Web.HTML.HTMLDocument (body) | |
import Web.HTML.HTMLElement (toElement) | |
import Web.HTML.Window (document) | |
main :: Effect Unit | |
main = do | |
body <- body =<< document =<< window | |
case body of | |
Nothing -> throw "Could not find body." | |
Just b -> do | |
buttons <- mkButtons | |
render (buttons unit) (toElement b) | |
mkButtons :: Component Unit | |
mkButtons = do | |
component "Buttons" \_ -> React.do | |
count /\ setCount <- useState 0 | |
useAff count do | |
log ("From useAff: " <> show count) # liftEffect | |
useEffect count do | |
log ("From useEffect: " <> show count) | |
pure mempty | |
let | |
handleClick = handler_ <<< setCount | |
pure | |
$ R.div_ | |
[ R.button { onClick: handleClick (_ - 1), children: [ R.text "-" ] } | |
, R.div_ [ R.text (show count) ] | |
, R.button { onClick: handleClick (_ + 1), children: [ R.text "+" ] } | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment