Skip to content

Commit

Permalink
Made useState return a normal curried Effect function for setting
Browse files Browse the repository at this point in the history
  • Loading branch information
jjl committed Apr 25, 2019
1 parent 02dde94 commit c2cd0e7
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
11 changes: 6 additions & 5 deletions src/Reactix/Hooks.purs
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,11 @@ import Reactix.React ( Hooks, react, unsafeHooksEffect )
--- useState

-- | A state hook is a tuple of value and setter
type State state = Tuple state (EffectFn1 state Unit)
type State state = Tuple state (state -> Effect Unit)

-- | Given an Effect function returning an initial value, returns a State
useState :: forall s. (Unit -> Effect s) -> Hooks (State s)
useState s = hook $ \_ -> pure $ tuple $ react ... "useState" $ [ delay s ]

useState s = hook $ \_ -> pure $ currySecond $ react ... "useState" $ [ delay s ]
-- -- useReducer

-- type Reducer state action = Tuple state (EffectFn1 action Unit)
Expand Down Expand Up @@ -146,8 +145,7 @@ useLayoutEffect5 a b c d f e = _useLayoutEffect e $ args5 a b c d f
type Ref state = Tuple state (state -> Effect Unit)

useRef :: forall r. r -> Hooks (Ref r)
useRef r = hook $ \_ -> pure $ friendly $ tupleCurrent $ react ... "useRef" $ [ r ]
where friendly (Tuple v s) = Tuple v (runEffectFn1 s)
useRef r = hook $ \_ -> pure $ currySecond $ tupleCurrent $ react ... "useRef" $ [ r ]

-- useContext

Expand Down Expand Up @@ -185,6 +183,9 @@ tupleCurrent = runFn2 _tupleCurrent Tuple

foreign import _tupleCurrent :: forall a b c. Fn2 (a -> b -> Tuple a b) c (Tuple a b)

currySecond :: forall a b c. Tuple a (EffectFn1 b c) -> Tuple a (b -> Effect c)
currySecond (Tuple a b) = Tuple a (runEffectFn1 b)

hook :: forall v. (Unit -> Effect v) -> Hooks v
hook = unsafeHooksEffect <<< delay

Expand Down
2 changes: 1 addition & 1 deletion test/Reactix/React/Spec.purs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ counterCpt = R.hooksComponent "Counter" cpt
pure $ div { className: "counter" }
[ button { type: "button", onClick: onclick setY (y + 1) } [ text "++" ]
, div {} [ text (show y) ] ]
onclick set to = mkEffectFn1 $ \e -> runEffectFn1 set to
onclick set to = mkEffectFn1 $ \e -> set to

counterTest :: Spec Unit
counterTest =
Expand Down

0 comments on commit c2cd0e7

Please sign in to comment.