According to the documentation, useAff
is defined like this.
useAff :: forall key a. Eq key => key -> Aff a -> Hook (UseAff key a) (Result a)
Aff
is used for asynchronous effects. The docs on Aff
is a great place to learn about it!
Back to useAff
, when I first encountered this function I didn't
really know what it does. Sure, the type signature gave me some clues, like I need to give me it some key
with the condition that this key has to have an Eq
instance. The second parameter needs an Aff
, then it will return some type Hook
. Based on the second parameter this tells me that this is the function I need to make asynchronous effects.
This is my login component using useAff
but it didn't start out like this. My first implementation for useAff
was something like this
useAff unit $ do
submitLogin isSubmitting { email: login.email, password: login.password }
I was very confused on why it's only getting called once after render. I also
tried something like this.
useAff "pleaseWork" $ do
submitLogin isSubmitting { email: login.email, password: login.password }
Of course that didn't work.
I kept going back to this example and this repo, and kept wondering what I'm doing different. Then I had my "eureka" moment. I said to myself, "Maybe the Eq
constraint has something to do with it. Maybe it checks the equality of the key
parameter I passed in, and if it changes something will happen?" So I changed my implementation to this
useAff login $ do
submitLogin isSubmitting { email: login.email, password: login.password }
login
changes when the button is clicked on this line.
It worked!
References
Purescript React Basic Hooks Documentation
Purescript React Basic Hooks Examples
Purescript React Basic Dogs repo by Peter Murphy
Miles Frain for answering my questions in fpchat
Top comments (0)