Skip to content

Instantly share code, notes, and snippets.

@alex-dixon
Forked from madbonkey/typeahead.cljs
Created April 2, 2018 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex-dixon/ca2a39dfff76528e764a7111329b67b6 to your computer and use it in GitHub Desktop.
Save alex-dixon/ca2a39dfff76528e764a7111329b67b6 to your computer and use it in GitHub Desktop.
(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