Michael / Jun 03 2022 / Published
Remix of ClojureScript + JavaScript by
Martin Kavalar
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 namespacejs/windowjs/console;; 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)js/Math.PI(.-PI js/Math)Create JS stuff from CLJS
;; Create a JS obj(def obj js {:key "value"});; the objobj;; 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]})Promises
(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 "https://gist.githubusercontent.com/AutoScreencast/25dc46fe6c7d2f6a9da34cdfd95c866e/raw/06b00740abd3ee1f1cc199477ab8462a1557c519/products.json")(defn get-products-from-api [] (-> (js/fetch api-endpoint) (.then (.json %)) (.then (js->clj % :keywordize-keys true)) (.then (handler %)) (.catch (error-handler %))))(get-products-from-api)state