zengod
zengod

Reputation: 1174

How to render dom components in reagent asynchronously?

I make an http request and try to put the returned val into a reagent component like so:

[div
    (a/take! (http/get "http://localhost:5000/data"))
             #(into [:div]
                     (map render-method
                          (into [] (map (fn [res] (:name res)) (-> % :body :results))))

                     )
                )
]

But this understandably doesn't work because the a/take! itself doesn't return the component. So how does one make the async get request work with reagent?

Upvotes: 1

Views: 193

Answers (1)

Walton Hoops
Walton Hoops

Reputation: 864

You can't do this. Instead you need to store the result in an atom, and reagent will rerender for you once it's loaded.

(def data (reagent/atom nil))

(defn fetch-data []
  (take! (http/get "http://localhost:5000/data") #(reset! data %)))

(defn names-list []
  [:div
   (doall (map :name @data))])

(defn my-component []
  [:div
   (if @data
     [names-list]
     [:div "loading"])])

Upvotes: 3

Related Questions