day8 / re-frame

A ClojureScript framework for building user interfaces, leveraging React
http://day8.github.io/re-frame/
MIT License
5.42k stars 715 forks source link

Resetting input value after dispatching #651

Closed patapizza closed 3 years ago

patapizza commented 3 years ago

Hey,

I'm having issues with resetting an input field after dispatching an event. Most times the input value doesn't update, although the underlying atom is updated.

Here's the snippet:

(defn my-input []
  (r/with-let [new-value-ref (r/atom "")]
    (let [new-value @new-value-ref
          submit! (fn [e]
                      (let [x (string/trim new-value)]
                        (when-not (string/blank? x)
                          (reset! new-value-ref "")
                          ;; without this it works
                          (rf/dispatch [:do-something x]))
                        (.preventDefault e)))]
       [:input
        {:type "text"
         :placeholder "Add"
         :value new-value
         :on-change #(reset! new-value-ref (-> % .-target .-value))
         :on-key-down #(case (.-which %)
                         13 (submit! %)
                         nil)}])))

I tried with dispatch-sync as well.

Inlining the function at callsites works a bit more reliably, but this is quite redundant.

What am I missing?

Thanks!

mainej commented 3 years ago

I tried to reproduce this, but can't. I copied your snippet, adding a :do-something event handler. I can type into the input. When I hit return, the dispatch function is called and the input is cleared.

Do you get something different? What sequence of steps do you take and exactly when do you see the unexpected behavior? Perhaps it would be useful to know which version of reagent and re-frame you're using, as well as what browser.