Fork me on GitHub
#helix
<
2023-04-02
>
pbranes00:04:44

I am trying to register an event listener with a use-effect hook. Right now I just have a simple function that logs to a console but not seeing the log statement. Also, how do I return a callback to remove the event listener? Is it just another line below my addEventListener?

(hooks/use-effect []
                      :once
                      (.addEventListener js/window "onkeydown" (fn [e] (js/console.log "checkkey"))) )

hifumi12301:04:10

hooks/use-effect is tricky in Helix because, unlike React’s useEffect, there is an implicit closure in the body. Consequently, the following code is incorrect

(hooks/use-effect :once
  (fn mount []
    ...
    (fn unmount [] ...)))
whereas the following code is correct
(hooks/use-effect :once
  ...
  (fn unmount [] ...))

hifumi12301:04:48

So to answer your event listener question: you’ll want something like this

(hooks/use-effect :once
  (js/window.addEventListener event handle-event)
  (fn unmount []
    (js/window.removeEventListener event handle-event)))

pbranes01:04:09

Ok, thanks that makes sense... I was about ask a bunch of questions. Let me give that a try.

pbranes02:04:37

Finally got my code to work with your suggestion and had to change "onkeydown" to "keydown" for the event. Thanks @hifumi123

👍 2
2