Last active
June 29, 2020 13:27
-
-
Save madbonkey/baf1417be520b27cf94a1fb14637ecbe to your computer and use it in GitHub Desktop.
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
(ns myapp.typeahead | |
(:require [reagent.core :as r] | |
[goog.functions :as gf] | |
[myapp.api :as api])) | |
(defn input-control [props] | |
(let [value (r/atom (:default-value props "")) | |
local-change #(reset! value (.. % -target -value))] | |
(fn [{:keys [on-change] :as props}] | |
[:input (assoc props | |
:value @value | |
:on-change (comp #(when (fn? on-change) (on-change %)) | |
local-change))]))) | |
(defn create-typeahead-fetch [opts state] | |
;; or however you want to build your fetch handler | |
(gf/debounce | |
(partial api/fetch (:remote opts)) | |
(:debounce-ms opts 150))) | |
(defn typeahead [opts] | |
(let [state (r/atom {:open? false | |
:loading? false | |
:results nil | |
:error nil}) | |
fetch (create-typeahead-fetch state opts) | |
toggle #(swap! state update :open? not)] | |
(fn [opts] | |
[:div | |
(if (:open? @state) | |
[input-control | |
{:default-value (:default-value opts "") | |
:on-change fetch}] | |
[button | |
{:on-click toggle} | |
"Show search"]) | |
(if (:loading? @state) | |
[:div "Loading"] | |
[:div (str (count (:results @state)) " results")])]))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment