purescript-react / purescript-react-basic-hooks

An implementation of React hooks on top of purescript-react-basic
https://pursuit.purescript.org/packages/purescript-react-basic-hooks/
Apache License 2.0
198 stars 31 forks source link

Foreign importing hooks #57

Open dnikolovv opened 2 years ago

dnikolovv commented 2 years ago

How would one approach this?

For example, use-on-click-outside or use-event-listener?

pete-murphy commented 2 years ago

I don't have much experience using FFI for hooks, but I put together a small example to give one idea of how you could go about it here: https://github.com/ptrfrncsmrph/demo-foreign-import-hooks/blob/main/src/Foreign/Hooks.purs

Usage would look like: https://github.com/ptrfrncsmrph/demo-foreign-import-hooks/blob/eb7523b16957df1465d79c81bb87b3178a8ff0da/src/App.purs#L14-L35

In PureScript I don't think we have a giant sum type representing all the possible event types in this WindowEventMap (at least that I'm aware of) so you'd probably just want to have a smaller sum type of the events you want to handle

In my example I've got the mouseEvent argument required in useOnClickOutside, though it's optional in TS. You could use a Maybe or to get the same convenience of allowing caller to omit it, you could probably do something with https://github.com/joneshf/purescript-option#how-to-make-a-function-with-required-and-optional-values (though I haven't used that library).

pete-murphy commented 2 years ago

I'm not sure if it's good practice to leave the internal hooks opaque in something like

newtype UseEventListener hooks = UseEventListener hooks

instead of typing them out like in https://github.com/megamaddu/purescript-react-basic-hooks/blob/4904b69821579f2c1fc3cac9f730892380216661/src/React/Basic/Hooks/Aff.purs#L58-L63

I'd imagine you'd want to leave them as just opaque hooks because you don't own the implementation 🤷.

dnikolovv commented 2 years ago

Wow, thanks! Maybe this should make it into the docs or at least the cook books?