ClojureScript <-> JavaScript Interop

Work in progress ...

Let's look at some stuff in the global (JS) scope

;; Everything in the global scope looks like it's from an 
;; automatically required namespace
;; we can print to the console - open dev tools
(js/console.log "Hello from CLJS")
;; alternative way to do it
(.log js/console "Hello again from CLJS")
(js/Math.max 1 3 4)
(.-PI js/Math)
Create JS stuff from CLJS
;; Create a JS obj
(def obj #js {:key "value"})
;; the obj
;; property access
(.-key obj)
;; this works too
(.. obj -key)
;; nested value "collections" need their own #js to be converted
(def another-obj #js{:key "value"
                     :nested-obj #js {:key "value2"}
                     :nested-array #js [1,2,3,4,5]}) 
(.-key (.-nested-obj another-obj))
(.. another-obj -nested-obj -key)
(-> another-obj .-nested-obj .-key)
Convert JS to CLJS
(js->clj #js [1 2 3 4 5])
Convert CLJS to JS
(clj->js {:key "value" :vector [1 2 3 4 5]})
(def state (atom {}))
(defn handler [response]
  (swap! state assoc :products response))
(defn error-handler [err]
  (.log js/console (str "Error: " (.-message err))))
(def api-endpoint "")
(defn get-products-from-api []
  (-> (js/fetch api-endpoint)
      (.then #(.json %))
      (.then #(js->clj % :keywordize-keys true))
      (.then #(handler %))
    (.catch #(error-handler %))))
Runtimes (1)