lilactown / helix

A simple, easy to use library for React development in ClojureScript.
Eclipse Public License 2.0
627 stars 52 forks source link

add check for IStateUpdater protocol before applying spread-updater #97

Closed lilactown closed 2 years ago

lilactown commented 2 years ago

This potentially fixes an issue where when passing in the setter function returned by use-state, the setter is accidentally passed two arguments and attempts to call (apply arg1 ,,,), leading to runtime errors.

Example:

(defnc my-component
  []
  (let [[state set-state] (hooks/use-state 0)]
    ($ some-other-component {:on-event set-state})))

If the handler passed into :on-event gets called with two arguments, then this will fail at runtime with a hard to debug error.

With this PR, the behavior instead will be that the set-state function will check to see if the first argument is either a function, a multimethod or if implements a special protocol. If it matches one of those, then it will do as it does today and try and call it like a function just like swap!. If it does not match one of those, then it will set the state to be whatever the first argument is and ignore the rest of the arguments.