Skip to content

Instantly share code, notes, and snippets.

@pesterhazy
Created July 20, 2018 17:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pesterhazy/1afd10dda0449121616b54868e3d9452 to your computer and use it in GitHub Desktop.
Save pesterhazy/1afd10dda0449121616b54868e3d9452 to your computer and use it in GitHub Desktop.
Debounce reagent input components safely
(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