Thread/sleep in clojurescript - clojure

Hellow everyone.
This is a block of code in events.cljs file. There is a button on the page that I want when I click that, a text appears on the page and disappear after 3 seconds. Here I wanted to assoc the text to the db after clicking the button and dissoc it after 3 seconds but there is an error that Thread namespace not found, from Thread/sleep line.
Can anyone help me how I should fix that please?
Thank you
(rf/reg-event-db
::niloofar
(fn [db [_]]
(do
(assoc db :greeting "hi")
(Thread/sleep 3000)
(dissoc db :greeting))))

You should create a new effect that dissocs the value and use it with :dispatch-later, something like:
(rf/reg-event-fx ::show
(fn [{db :db} _]
{:db (assoc db :greeting "hi")
:dispatch-later {:ms 3000 :dispatch [::-hide]}))
(rf/reg-event-db ::-hide
(fn [db _]
(dissoc db :greeting)))

Related

How to get files from <input type='file' …/> in ClojureScript

I'm trying to get image file in input field but I could not do it. Here is the code:
:on-change (fn [_]
(this-as this
(println "Files: " (.-files this))))
But (.-files this) returns nil.
Any ideas?
P.S: I would like to upload this image to my server.
Here is a workable snippet from our project:
:on-change
(fn [this]
(if (not (= "" (-> this .-target .-value)))
(let [^js/File file (-> this .-target .-files (aget 0))]
;; your logic here ...
;; now reset the widget to let user upload a new one
(set! (-> this .-target .-value) ""))))
Hope this would help.
To expand on Albert's answer (and because my edits were rejected):
Instead of using goog.object/get as below (and in his answer with o/get):
(let [dom (goog.object/get event "target")
file (goog.object/getValueByKeys dom #js ["files" 0])]))
You can also use regular interop forms in ClojureScript:
:on-change (fn [event]
(let [files (.. event -target -files) ; returns JS Array
file (first files)]
(do-something-with file)]))
you must first get the dom node from somewhere. In React world this might not be the dom since they are syntactic events.
:on-change (fn [event]
(let [dom (goog.object/get event "target")
file (goog.object/getValueByKeys dom #js ["files" 0])]))
Or using regular interop forms in ClojureScript:
:on-change (fn [event]
(let [files (.. event -target -files) ; returns JS Array
file (first files)]
(do-something-with file)]))
https://reactjs.org/docs/handling-events.html

No view is being rendered in re-frame app

Here's a simple re-frame app that I tried to create based on the existing example project in re-frame's github repo. But it is only displaying things from the html file. Seems like no event is being dispatched. Can anyone point out what am I doing wrong? Thanks.
(ns simple.core
(:require [reagent.core :as reagent]
[re-frame.core :as rf]
[clojure.string :as str]))
(rf/reg-event-db
:rand
(fn [db [_ _]]
(assoc db :winner ( + 2 (rand-int 3)))))
(rf/reg-sub
:winner
(fn [db _]
(:winner db)))
(def participants ["Alice" "Bob" "Ellie"])
(defn winners-name
[idx]
(get participants idx))
(defn show-winner
[]
[:h1
(winners-name
(#(rf/subscribe [:winner])))])
(defn ui
[]
[:div
[:h1 "Lottery"]
[show-winner]])
(defn ^:export run
[]
(rf/dispatch-sync [:rand])
(reagent/render [ui]
(js/document.getElementById "app")))
The :rand handler will produce nil most times since you are adding 2 to the generated value and the participants vector only has 3 entries.
The issue is caused because of a pair of extra parenthesis around the deref thing. So the function winners-name is treating it as a list instead of an integer.
(winners-name
(#(rf/subscribe [:winner]))

How should one handle AJAX success/error responses in Clojure re-frame?

I love re-frame, but I realize that I'm having a bit of trouble finding a nice pattern for handling AJAX responses.
My situation is the following:
I have a "global" event handler that triggers some AJAX call and dispatches to some other global event handler, depending on whether that call was successful, e.g.:
(reg-event-db :store-value
(fn [db [_ value]]
(do-ajax-store value
:on-success #(dispatch [:store-value-success %])
:on-error #(dispatch [:store-value-error %])
db))
(reg-event-db :store-value-success
(fn [db [_ result]]
(assoc db :foobar result)))
(reg-event-db :store-value-error
(fn [db [_ error]]
(assoc db :foobar nil
:last-error error)))
(I am aware of reg-event-fx and stuff, I'm just avoiding it here for the sake of brevity and because I think it does not make any difference for my problem).
I also have (multiple, distinct) UI components that might trigger the :store-value event, like so:
(defn button []
(let [processing? (reagent/atom false)]
(fn button-render []
[:button {:class (when #processing? "processing")
:on-click (fn []
(reset! processing? true)
(dispatch [:store-value 123]))}])))
So in this case the component has local state (processing?) that is supposed to depend on whether the AJAX call is still in progress or not.
Now, what is the proper pattern here to have the button component react to the events :store-value-success and :store-value-error in order to reset the processing? flag back to false after the AJAX call has finished?
Currently, I'm working around that problem by passing down callbacks but that seems really ugly because it clutters the event handlers' code with stuff that does not really belong there.
The best solution that I've thought of would be to have the button component being able to hook into the :store-value-success and :store-value-error events and install its own handler for those events, like this:
(defn button []
(let [processing? (reagent/atom false)]
(reg-event-db :store-value-success
(fn [db _]
(reset! processing? false)))
(reg-event-db :store-value-error
(fn [db _]
(reset! processing? false)))
(fn button-render []
[:button {:class (when #processing? "processing")
:on-click (fn []
(reset! processing? true)
(dispatch [:store-value 123]))}])))
However, that does not work. As it seems, re-frame does not allow multiple event handlers per event. Instead, a subsequent invocation of reg-event-db on one single event id will replace the previous event handler.
So how do you guys handle situations like this?
I think reg-event-fx (src) might indeed help solve your problem.
You could add a subscription that watches app-state e.g.
(rf/reg-sub
:app-state
(fn [db]
(get db :app-state)))
and add this to your button, perhaps with a state function e.g.
(defn btn-state [state]
(if (= state :processing)
"processing"))
And then in the AJAX handler, you could add an fx to update the state-
(reg-event-fx ;; -fx registration, not -db registration
:ajax-success
(fn [{:keys [db]} [_ result]]
{:db (assoc db :app-state :default)
:dispatch [:store-value-success result]}))
(reg-event-fx ;; -fx registration, not -db registration
:ajax-error
(fn [{:keys [db]} [_ result]]
{:db (assoc db :app-state :default)
:dispatch [:store-value-error result]}))
and update the AJAX handler
(reg-event-db :store-value
(fn [db [_ value]]
(do-ajax-store value
:on-success #(dispatch [:ajax-success %])
:on-error #(dispatch [:ajax-error %])
db))
This would be one way to handle it via -fx. I think you have already started to see the need for tracking app state, and I think bumping it up into the subscriptions would help with complexity, at which point your button render is greatly simplified.
(defn button []
[:button {:class (btn-state #app-state)
:on-click (dispatch [:store-value 123]))}])))
As others have mentioned, I would recommend to use http-fx and make processing? part of your global state. The code would look like this:
Events:
(reg-event-fx
:request
(fn [{:keys [db]} [_ method url data]]
{:http-xhrio {:method method
:uri url
:params data
:format (ajax/json-request-format)
:response-format (ajax/json-response-format {:keywords? true})
:on-success [:success-response method url]
:on-failure [:error-response method url]}
:db (assoc db :processing? true)}))
(reg-event-db
:success-response
(fn [db [_ method url result]]
(assoc db :foobar response
:processing? false)}))
(reg-event-db
:error
(fn [db [_ method url result]]
(assoc db :foobar nil
:last-error result
:processing? false)}))
Subscriptions:
(reg-sub
:processing
(fn [db _]
(:processing? db)))
View:
(defn button []
(let [processing? #(rf/subscribe [:processing])]
[:button {:class (when processing? "processing")
:on-click #(dispatch [:store-value 123]))}])))
Hint: You could reuse this code with all your requests.

clojure (add-watch) not notifying when changes are made on the clipboard

I'm writing a small tool in clojure and want to know when there's been a change on the clipboard. Here's a simplified version of what's going on.
(:import java.awt.Toolkit)
(:import (java.awt.datatransfer Clipboard
ClipboardOwner
Transferable
StringSelection
DataFlavor
FlavorListener))
(defn get-clipboard [] (. (Toolkit/getDefaultToolkit)
(getSystemClipboard)))
(defn get-content []
(.getContents (get-clipboard) nil))
(def content (agent (get-content)))
(defn watch [key f]
(add-watch content key f))
(defn -main []
(while (not= content "banana-man")
(watch :watcher
(fn [key agent old-state new-state]
(prn "-- agent Changed --")
(prn "key" key)
(prn "atom" agent)
(prn "old-state" old-state)
(prn "new-state" new-state)))))
I've added in a while loop just to keep the main function from shutting down immediately.
This runs without throwing any errors, but does not report when changes have been made on the clipboard or stop the while loop when I copy bannan-man to the clipboard. I've been struggling with this for a few weeks now and I'm sure I'm missing something simple. If anyone has some advice I would really appreciate it!
For starters, content is an agent, so it will never be equal to a string. You should deref the agent using # in order to make that comparison.
The while loop is not needed to prevent exit. If you use the agent thread pool, Clojure will not shut down until you explicitly run shutdown-agents. But we will need it to manage your agent updates.
content is not going to change after your initial assignment unless you explicitly send it an updating function with send or send-off. Don't let the name mislead you, agents are not autonomous, and are not scheduled or repeated tasks. Try something like this:
(defn -main []
(watch :watcher
(fn [key agent old-state new-state]
(prn "-- agent Changed --")
(prn "key" key)
(prn "atom" agent)
(prn "old-state" old-state)
(prn "new-state" new-state)))
(while (not= #content "banana-man")
(send-off content (fn [& _] (get-content)))
(Thread/sleep 250))
(shutdown-agents))

clojurescript + reagent issue

I am working on a simple web-app using clojurescript and reagent. I would like to create a simple "tab" component, which will contain (for starters) a text-input component.
The app has 2 tabs and the user has the option to choose a tab and I want to "preserve" the values in each of these two tabs.
Here's the code:
(defn atom-input [value]
[:input {:type "text"
:value #value
:on-change #(reset! value (-> % .-target .-value))}])
(defn simple-tab [index]
(let [pg-index (atom 1)
a (atom 0)]
(fn []
[:div
[:h4 (str "index: " #index)]
[atom-input a]])))
(defn main-page []
(let [index (atom 0)]
[:div.container
[:div.row
[:button {:on-click (fn [] (reset! index 0))} "select tab 1"]
[:button {:on-click (fn [] (reset! index 1))} "select tab 2"]]
[:div.row
[simple-tab index]]]))
(defn ^:export run []
(reagent/render-component
(fn [] [main-page])
(.-body js/document)))
The problem is that when I switch the tab, the components share the values of the input field - what am I please doing wrong here?
Thank you so much for your help!
The problem is you're passing a (atom 0) to the atom-input control: [atom-input a].
This caused the same atom value to be shared between your tabs.
If you don't want to share the value, you'll need change a to a map: a (atom {}) and pass the map and the index to atom-input, e.g.:
(defn atom-input [value index]
[:input {:type "text"
:value (or (get #value index) "")
:on-change #(swap! value assoc index (-> % .-target .-value))}])
(defn simple-tab [index]
(let [pg-index (atom 1)
a (atom {})]
(fn []
[:div
[:h4 (str "index: " #index)]
[atom-input a #index]])))
A better approach, IMHO, is to use cursor so you don't need to pass the index & the whole map to atom-input, e.g.:
(defn atom-input [value]
[:input {:type "text"
:value (or #value "")
:on-change #(reset! value (-> % .-target .-value))}])
(defn simple-tab [index]
(let [pg-index (atom 1)
a (atom {})]
(fn []
[:div
[:h4 (str "index: " #index)]
[atom-input (reagent/cursor [#index] a)]])))
I think there are a couple of problems here because you are mixing up application data (state) and display logic data (i.e. DOM). If you keep the two things distinct i.e. maintain your application state in one atom and data relating to component display in another, then things may be a bit cleaner.
Your simple-tab component does not need to know anything about the tab state. It just needs to know about the app state i.e. the value entered/stored via atom-input. Therefore, rather than passing it index, pass it the atom you want it to use. this would require some higher level logic to determine the call. for example, if you had a number of tabs, you might have something like
(condp = #index
0 [simple-tab tab0-atom]
1 [simple-tab tab1-atom]
...
n [simple-tab tabn-atom])
or you could modify simple-tab so that the value passed in i.e. index value is used as a key into the app-state - a cursor would be easiest I think i.e.
(def app-state (r/atom {:tabs {0 nil 1 nil}}})
(defn simple-tab [index]
(let [val-cur (r/cursor app-state [:tabs index])]
[atom-input val-cur]))
You are using a form-2 component, that is, a component that returns a function.
More details here : https://github.com/Day8/re-frame/wiki/Creating-Reagent-Components#form-2--a-function-returning-a-function
When doing so, only the returned function is called so your atom-inputs are sharing the same atom.
Also, you should use the same argument in the inner function
(defn simple-tab [index]
(let [pg-index (atom 1)
a (atom {})]
(fn [index]
[:div
[:h4 (str "index: " #index)]
[atom-input a #index]])))
In your case, you are passing an atom so this is not important but you could have error in the future if you forgot this.
Concerning the broader architecture, I would advise you to use a single global atom. Try to have as much as possible state in this atom and avoid component local state so this is easier to reason about.
You could also name your tabs like :product :users and use a multimethod to render the correct tab based on the selected one. This is easier to read and easier to add new tabs in the future.