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"))) )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 [] ...))
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)))
Ok, thanks that makes sense... I was about ask a bunch of questions. Let me give that a try.
Finally got my code to work with your suggestion and had to change "onkeydown" to "keydown" for the event. Thanks @hifumi123