Fork me on GitHub
Emi Gal18:07:09

Trying to get data from an API and display it into a web page. I can pull the data using cljs-http, I can view the data in the REPL, but when I try to display the data in the webpage, it shows nothing (and throws no errors). Any idea what I might be doing wrong? Here’s the code:

(def helium-api "MY_API_URL")

(def api-data (atom {}))

(defn get-data
  (go (let [response (<! (http/get helium-api
                                ;; parameters
                                   {:with-credentials? false}))]
        (reset! api-data (:body response)))))

(def helium-status (-> @api-data :data :status :online))

(defn home-panel
      {:class (styles/level1)}
      (str "Helium status is " helium-status ".")]])


In REPL, there's a delay between (get-data) and (def helium-status ...). But when you use it as a whole, there's none - the request isn't finished by the time you try to access the results in @api-data. go is asynchronous - it returns immediately, without blocking.

Emi Gal19:07:18

any solutions to that?


Assuming you're using Reagent, do all these steps: • Don't store the data in helium-status • Switch from the built-in atom to the reagent.core/atom one • Use the ratom directly in home-panel This way, when the data comes, home-panel will be automatically re-rendered. Check out Reagent multiple examples and documentation for the details.

Emi Gal19:07:01

Awesome, thank you! Using re-frame, so I’ll just save data to re-frame db and then display it using a sub. Thank you! 🙏

👍 3

Many have done such a mistake before. :D

🙃 3