Elmish.Hooks
- Package
- purescript-elmish-hooks
- Repository
- collegevine/purescript-elmish-hooks
A React hook-like library for Elmish. Uses a continuation monad to encapsulate state or effects.
import Elmish.Hooks (withHooks, useEffect, useState)
import Elmish.Hooks as Hooks
todos :: ReactElement
todos = withHooks Hooks.do
todos /\ setTodos <- useState []
useEffect do
todos <- API.fetchTodos
liftEffect $ setTodos todos
Hooks.pure $ H.fragment $ todoView <$> todos
Re-exports from Elmish.Hooks.Type
#withHooks Source
withHooks :: forall t. Hook' t ReactElement -> ReactElement
Unwraps a Hook ReactElement
, which is usually created by using one or
more hooks and then using pure
to encapsulate a ReactElement
. E.g.:
view :: ReactElement
view = withHooks Hooks.do
name /\ setName <- useState ""
Hooks.pure $ H.input_ "" { value: name, onChange: setName <?| eventTargetValue }
#mkHook Source
mkHook :: forall msg state t a. ComponentName -> ((a -> ReactElement) -> ComponentDef msg state) -> Hook' t a
Given a ComponentName
and a function to create a ComponentDef
(from a
render function a -> ReactElement
), mkHook
creates a Hook a
. When
creating a hook with mkHook
, you’ll need to create a HookType
by
foreign import
ing it.
As an example of how to use mkHook
, useEffect
uses it like so:
foreign import data UseEffect :: Type -> HookType
useEffect :: Aff Unit -> Hook (UseEffect Unit) Unit
useEffect init =
mkHook (ComponentName "UseEffect") \render ->
{ init: forkVoid init
, update: \_ msg -> absurd msg
, view: \_ _ -> render unit
}
#bind Source
bind :: forall ta tb tr a b. ComposedHookTypes ta tb tr => Hook' ta a -> (a -> Hook' tb b) -> Hook' tr b
#type (<>) Source
Operator alias for Elmish.Hooks.Type.AppendHookType (right-associative / precedence 6)
Re-exports from Elmish.Hooks.UseEffect
#useEffect Source
useEffect :: Aff Unit -> Hook (UseEffect Unit) Unit
The useEffect
hook takes an effect (Aff
) to run and runs it in the
init
of the resulting component. E.g.:
todos :: ReactElement
todos = withHooks Hooks.do
todos /\ setTodos <- useState []
useEffect do
todos <- API.fetchTodos
liftEffect $ setTodos todos
Hooks.pure $ H.fragment $ todoView <$> todos
Re-exports from Elmish.Hooks.UseState
#useState Source
useState :: forall state. state -> Hook (UseState state) (state /\ (Dispatch state))
The useState
hook takes an initial state and returns a Hook
encapsulating the current state and a setState
function. E.g.:
view :: ReactElement
view = withHooks Hooks.do
visible /\ setVisible <- useState false
Hooks.pure $
H.fragment
[ H.button_ "" { onClick: setVisible $ not visible } "Toggle visibility"
, if visible
then H.div "" "Content"
else H.empty
]