I see an example of Ajax call in the re-frame docs:
(reg-event-fx ;; <-- note the `-fx` extension
:request-it ;; <-- the event id
(fn ;; <-- the handler function
[{db :db} _] ;; <-- 1st argument is coeffect, from which we extract db
;; we return a map of (side) effects
{:http-xhrio {:method :get
:uri "http://json.my-endpoint.com/blah"
:format (ajax/json-request-format)
:response-format (ajax/json-response-format {:keywords? true})
:on-success [:process-response]
:on-failure [:bad-response]}
:db (assoc db :loading? true)}))
Can I just call the event in the main function:
(reframe/dispatch-sync [:request-it])
to load the initial values? I need to load the initial values and then render the views.
UPDATE
I did it using this function:
(reframe/reg-event-db
:process-response
(fn
[db [_ response]]
(-> db
(assoc :loading? false) ;; take away that "Loading ..." UI
(assoc :test (js->clj response))
(assoc :questions (js->clj (:questions response))))))
Related
The question is how to send to a nodejs app the result of a go block
i found a solution with callback
but i need a solution with promise
Promise solution?
Clojurescript app
(defn foo []
(go 1))
;;how to change foo,wrap to promise?, so node app can await to get the 1
;;i used 1 for simplicity in my code i have something like
;;(go (let [x (<! ...)] x))
Node app
async function nodefoo() {
var x = await foo();
console.log(x); // i want to see 1
}
Callback solution (the one that works now)
So far i only found a way to pass a cb function, so this 1 goes back to node.js app
Clojurescript app
(defn foo1 [cb]
(take! (go 1)
(fn [r] (cb r))))
Node app
var cb=function () {....};
foo1(cb); //this way node defined cb function will be called with argument 1
But i dont want to pass a callback function, i want node.js to wait and get the value.
I want to return a promise.
This function takes a channel and returns a Javascript Promise that resolves with the first value the channel emits:
(defn wrap-as-promise
[chanl]
(new js/Promise (fn [resolve _]
(go (resolve (<! chanl))))))
Then to show usage:
(def chanl (chan 1))
(def p (wrap-as-promise chanl))
(go
(>! chanl "hello")
(.then p (fn [val] (println val))))
If you compile that and run it in your browser (assuming you called enable-console-print!) you'll see "hello".
It is also possible to extend the ManyToManyChannel type with extend-type.
Here's a naif implementation using a similar wrap-as-promise function
(require '[clojure.core.async.impl.channels :refer [ManyToManyChannel]])
(defn is-error? [val] (instance? js/Error val))
(defn wrap-as-promise
[channel callback]
(new js/Promise
(fn [resolve reject]
(go
(let [v (<! channel)]
(if (is-error? v)
(reject v)
(resolve (callback v))))))))
(extend-type ManyToManyChannel
Object
(then
[this f]
(wrap-as-promise this f)))
(def test-chan (chan 1))
(put! test-chan (new js/Error "ihihi"))
(put! test-chan :A)
(defn put-and-close! [port val]
(put! port val)
(async/close! port))
(-> test-chan
(.then (fn [value] (js/console.log "value:" value)))
(.catch (fn [e] (js/console.log "error" e)))
(.finally #(js/console.log "finally clause.")))
Is there a way in Clojurescript create an async function or a macro wrap a function into a Promise to simulate it?
My current use-case is to replace the following function that takes a callback by its async version - btw this is for an AWS lambda function.
// Old style
function(args, callback) {
// Use callback(e) for errors
// Use callback(null, value) for the result
}
// New style
async function(args) {
return value; // success path
throw new Error(); // error path
}
Given that this is Clojurescript, using await is not the question. And I know this can simply return a Promise to comply with the async requirement.
So it resolves to some sugar code to create the Promise, catch all errors for me and calling resolve on the happy path or reject otherwise.
Browsing through clojure.core.async and docs -including the clojurescript reference, I haven't found anything.
Node 8 and newer ship with util.promisify that does what you want:
Takes a function following the common error-first callback style, i.e. taking a (err, value) => ... callback as the last argument, and returns a version that returns promises.
EDIT: I spent a bit writing a macro that does promisify and I'm safisfied with the result. Note that the macro needs to be saved in a CLJC file:
;; macros.cljc ;;;;;;;;;;
(ns server.macros)
(defmacro promisify [method obj params]
`(js/Promise.
(fn [resolve# reject#]
(~method ~obj ~params
(fn [err# result#]
(if err#
(reject# err#)
(resolve# result#)))))))
;; main.cljs ;;;;;;;;;;
(ns server.main
(:require-macros [server.macros :refer [promisify]])
(:require ["aws-sdk" :as aws]))
(defn main! []
(println "App loaded...")
(let [creds (aws/SharedIniFileCredentials. #js {:profile "example-profile"})
_ (set! (.-credentials aws/config) creds)
s3 (aws/S3.)]
(-> (promisify .listBuckets s3 #js {})
(.then #(println "DATA:" %))
(.catch #(println "ERROR:" %)))))
and the output is the same as before:
$ node target/main.js
App loaded...
DATA: #js {:Buckets #js [#js {:Name demo-test-bucket, :CreationDate #inst "2019-05-05T17:32:17.000-00:00"} #js {:Name subdomain.mydomain.com, :CreationDate #inst "2019-06-19T04:16:10.000-00:00"}], :Owner #js {:DisplayName username, :ID 9f7947b2d509e2338357d93e74f2f88a7528319ab3609b8d3b5be6b3a872dd2c}}
The macro is basically a Clojure version of this code.
EDIT 2: There's also this library that could be interesting if you really want to use core.async too.
I am making an HTTP request:
(defn main-panel []
(def API-URL "https://api.chucknorris.io/jokes/random")
(defn getFileTree []
(go (let [response (<! (http/get API-URL
{:with-credentials? false
:headers {"Content-Type" "application/json"}}))]
(:status response)
(js/console.log (:body response))))) ; prints a very complex data structure
(go
(let [result (<! (getFileTree))]
(.log js/console (:body result)))) ; prints null
:reagent-render
(fn []
[:h1 "kjdfkjndfkjn"]))
But I can't get to the "joke" in the returned object, array item 13:
How do I assign this value to a let or def?
Also, why does the second console.log print null?
Update
I am now moving on from using reagent atoms to reframe.
This is my component that successfully GETs data, updates the re-frame 'database':
(defn main-panel []
(def API-URL "https://api.chucknorris.io/jokes/random")
(def request-opts {:with-credentials? false})
(defn getFileTree []
(go (let [response (<! (http/get API-URL request-opts))]
(re-frame/dispatch [:update-quote response]))))
(defn render-quote []
(println (re-frame/subscribe [::subs/quote])) ;successfully prints API data as in screenshot below
(fn []
(let [quote-data (re-frame/subscribe [::subs/quote])
quote-text (if quote-data (:value quote-data) "...loading...")]
[:div
[:h3 "Chuck quote of the day"]
[:em quote-text]])))
(fn []
(getFileTree)
[render-quote]))
But this is the object I get back from the re-frame database:
As you can see it comes wrapped in the Reaction tags and I can't access the body or value any more. How do I access those?
I have a small working version using the reagent template. Create a new project (assuming you have Leiningen installed) with: lein new reagent chuck. This will create a project with many dependencies, but it works out of the box.
Next, edit the file at src/cljs/chuck/core.cljs and edit it so it looks like the following:
(ns chuck.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [reagent.core :as reagent :refer [atom]]
[cljs-http.client :as http]
[cljs.core.async :refer [<!]]))
(def api-url "https://api.chucknorris.io/jokes/random")
(def request-opts {:with-credentials? false
:headers {"Content-Type" "application/json"}})
(def api-response (atom nil))
(defn get-quote []
(go
(let [response (<! (http/get api-url request-opts))]
(println response)
(reset! api-response response))))
(defn render-quote []
(fn []
(let [quote-data (:body #api-response)
quote-text (if quote-data (:value quote-data) "...loading...")]
[:div
[:h3 "Chuck quote of the day"]
[:em quote-text]])))
(defn quote-page []
(fn []
(do
(get-quote)
[:div
[:header
[render-quote]]
[:footer
[:p "footer here"]]])))
;; -------------------------
;; Initialize app
(defn mount-root []
(reagent/render [quote-page] (.getElementById js/document "app")))
(defn init! []
(mount-root))
I'll explain the relevant bits:
init will bootstrap the basics of the front-end, but in our case it's just calls mount-root which starts reagent telling it to call quote-page and placing the results in the DOM replacing the element with the ID of app.
quote-page calls get-quote which will call the API using the cljs-http library. I'm not checking for errors here, but basically when the request completes (either success or error) it will read the results from the channel (using <!) and place the response in response. The key is that response is a nested ClojureScript map that you can inspect to check if the result was successful or not. Note that I'm also printing the results with println instead of JS interop (.log js/console xxx) because console.log will show the inner details of how the nested map is implemented, which is not relevant for this case.
One the response is available, I store the results of the response in an atom called api-response. The key here is that the atom will contain nothing for a bit (while the request completes) and then the response will be inside it and reagent will take care of detecting the change and re-rendering.
Finally, quote-page calls render-quote which generates the markup for rendering the quote or a placeholder while it loads.
To run the whole thing, open a terminal and run lein run which will start a web server listening on port 3000 by default. In another terminal, run lein figwheel which will compile the ClojureScript code for you. One figwheel is ready it will start a REPL, and you can open the address http://0.0.0.0:3000/ in your computer to view the page.
My re-frame views.cljs has:
(re-frame/dispatch [::re-graph/init
{:http-url "https://api.spacex.land/graphql"
:ws-url nil
:http-parameters {:with-credentials? false}}])
(re-frame/dispatch [::re-graph/query
"{ launches { id, mission_name } }" ;; your graphql query
[::update-data]])
My events.cljs has:
(re-frame/reg-event-db
::update-data
(fn [db [_ {:keys [data errors] :as payload}]]
(-> db
(assoc :errors errors)
(assoc :data data))))
But I keep getting this error:
core.cljs:3919 re-frame: no :event handler registered for: undefined
The solution is to include the nil for the query variables
(re-frame/dispatch
[::re-graph/query
"{launches {id, mission_name}}"
nil
[:add-launches]])
You should use :events/update-data in views.cljs. The :: refers to the current namespace (:views/update-data), and that event handler is not defined there, but in the events namespace.
Also note that you can use:
(-> db
(assoc :errors errors
:data data)))
saves you one assoc.
How can I submit multipart/formdata in ClojureScript? Is there any library that supports this? I can fallback to e.g. jquery.form.js but would prefer a plain ClojureScript solution.
I recently made a pull request to cljs-http to support form-data. Util r0man merges it, you can see instruction in my version's README at https://github.com/myguidingstar/cljs-http
Edited: The pull request has been merged. See the original repository instead.
This is how I did it:
(defn generate-form-data [params]
(let [form-data (js/FormData.)]
(doseq [[k v] params]
(.append form-data (name k) v))
form-data))
(defn upload [file]
(go (let [response (<! (http/post "http://localhost/upload"
{:body (generate-form-data {:file file})}))]
(prn (:status response))
(prn (:body response)))))
;; some-dom-element is a single file upload input
;; <input type="file">
(upload (-> some-dom-element .-files first))
If you don't want to use cljs-http, see cljs-http.core/request in its source code for how to make a direct call to XhrIo
https://github.com/r0man/cljs-http/blob/master/src/cljs_http/core.cljs
Take a look at cljs-http:
;; Form parameters in a POST request (simple)
(http/post "http://example.com" {:form-params {:key1 "value1" :key2 "value2"}})
;; Form parameters in a POST request (array of values)
(http/post "http://example.com" {:form-params {:key1 [1 2 3] :key2 "value2"}})
====== UPDATE =======
You'll need some iframe hack. Read this and this:
;; Imports
(:require [goog.events :as gev])
(:import [goog.net IframeIo]
[goog.net EventType]
(defn upload []
(let [io (IframeIo.)]
(gev/listen io
(aget goog.net.EventType "SUCCESS")
#(js/alert "SUCCESS!"))
(gev/listen io
(aget goog.net.EventType "ERROR")
#(js/alert "ERROR!"))
(gev/listen io
(aget goog.net.EventType "COMPLETE")
#(js/alert "COMPLETE!"))
(.setErrorChecker io #(not= "ok" (.getResponseText io)))
(.sendFromForm io (dom/by-id "form") "/upload")))