Created
July 20, 2018 17:49
-
-
Save pesterhazy/1afd10dda0449121616b54868e3d9452 to your computer and use it in GitHub Desktop.
Debounce reagent input components safely
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn debouncify | |
"Given a Reagent component cmp that expects an on-change callback prop idenfied | |
by handler-kw (by default, :on-change), return a component that debounces calls | |
to the callback until input settles down for delay-ms (by default, 200 ms)." | |
([cmp] (debouncify cmp {})) | |
([cmp {:keys [delay-ms handler-kw] | |
:or {handler-kw :on-change | |
delay-ms 200}}] | |
(assert (number? delay-ms)) | |
(assert (keyword? handler-kw)) | |
(fn [initial-props] | |
(let [!handler (atom (handler-kw initial-props)) | |
handler-debounced (gfun/debounce (fn [& args] (apply @!handler args)) | |
delay-ms)] | |
(r/create-class | |
{:display-name "Demo" | |
:component-will-receive-props | |
(fn [this [_ new-props]] | |
(reset! !handler (get new-props handler-kw))) | |
:reagent-render | |
(fn [props & children] | |
(into [cmp (assoc props handler-kw handler-debounced)] children))}))))) | |
;; example 1: input | |
(defn text-input-ui [props] | |
[:input props]) | |
(def text-input-debounced-ui (debouncify text-input-ui)) | |
;; example 2: button | |
(defn click-ui [props] | |
[:button props "CLICK"]) | |
(def click-debounced-ui (debouncify click-ui {:handler-kw :on-click})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment