|
- module Component.LoginAff where
-
- import Prelude
- import Data.Maybe ( Maybe(..), fromMaybe )
- import Data.Argonaut.Encode.Class ( encodeJson )
- import Data.Argonaut.Core ( Json )
- import Data.Either ( Either )
- -- Effect
- import Effect ( Effect )
- -- Aff
- import Affjax as AX
- import Affjax.ResponseFormat as ResponseFormat
- import Affjax.RequestBody as RequestBody
- import Effect.Aff ( Aff, never )
- -- React
- import React.Basic.Hooks as React
- import React.Basic.Hooks ( ReactComponent, component, Hook, UseState, useState, (/\) )
- import React.Basic.Hooks.Aff ( useAff )
- import React.Basic.DOM as R
- import React.Basic.Events ( handler, EventHandler )
- import React.Basic.DOM.Events ( preventDefault, stopPropagation, targetValue )
-
- mkLoginAff :: Effect ( ReactComponent {} )
- mkLoginAff = do
- component "LoginAff" $ const React.do
- isSubmitting/\setSubmitting <- useState false
- email <- useInput ""
- password <- useInput ""
- login/\setLogin <- useState { email: "", password: "" }
- useAff login $ do
- void $ submitLogin isSubmitting { email: login.email, password: login.password }
- pure $ setSubmitting \_ -> false
- pure
- $ R.form_
- [ R.input
- { placeholder: "email"
- , onChange: email.onChange
- }
- , R.input
- { placeholder: "password"
- , onChange: password.onChange
- }
- , R.button
- { onClick: handler ( preventDefault >>> stopPropagation >>> targetValue ) \_ -> do
- setSubmitting \_ -> true
- setLogin \_ -> login { email = email.value, password = password.value }
- , children: [ R.text "Sign-In" ]
- }
- ]
-
- type Login =
- { email :: String
- , password :: String
- }
-
- submitLogin :: Boolean -> Login -> Aff ( Either AX.Error Json )
- submitLogin isSubmitting login = do
- if not isSubmitting
- then never
- else do
- result <- AX.post ResponseFormat.json "http://localhost:8080/login"
- ( Just $ RequestBody.json $ encodeJson login )
- pure $ _.body <$> result
-
- useInput
- :: String
- -> Hook
- ( UseState String )
- { onChange :: EventHandler
- , value :: String
- }
- useInput initialValue = React.do
- value /\ replaceValue <- useState initialValue
- pure
- { onChange: handler
- ( preventDefault >>> stopPropagation >>> targetValue ) \val -> do
- replaceValue \_ -> fromMaybe "" val
- , value
- }
|