Search code examples
clojurescriptreagent

Clojurescript reagent text field does not display typed content when I add :on-change handler


I am following along with the Reagent SPA tutorial at http://yogthos.net/posts/2014-07-15-Building-Single-Page-Apps-with-Reagent.html.

The code I have so far is:

(def state (atom {:doc {} :saved? false}))

(defn set-value! [id value]
  (swap! state assoc :saved? false)
  (swap! state assoc-in [:doc id] value))

(defn get-value [id]
  (get-in @state [:doc id]))

(defn row [label body]
  [:div.row
   [:div.col-md-2 [:span label]]
   [:div.col-md-3 body]])

(defn text-input [id label]
  [row label
   [:input {:type "text"
            :class "form-control"
            :value (get-value id)
            :on-change #(set-value! id (-> % .-target .-value))}]])

(defn home-pg []
  [:div.container
   [:div.page-header [:h1 "Reagent Form"]]
   [text-input :first-name "First name"]])

Now when I run this and type text in the text box, nothing appears. When I remove the :on-change handler, whatever I type shows up. Can someone help me to understand what is going on?

Many thanks in advance!


Solution

  • I found the error. The very first line is using a regular Clojure atom. Instead it should use a reagent atom. Changing that line to

    (def state (r/atom {:doc { } :saved? false}))
    

    fixes the problem.