Writing re-frame events that do not change app-db - clojurescript

There are certain events that do not result in app-db changing. They only change the dom, e.g: init a custom scroll, getting the selected text, etc. How should I deal with them in re-frame, since the event handler requires to return a new app-db? I am getting around by returning the existing db, but it does not seem right. Is there a better way to do it? A few of my handlers look like this:
(re-frame/reg-event-db
:init-link-viewer
(fn [db [_ highlights]]
(utils/load-highlights highlights)
(utils/init-selection)
db))

You can use the reg-event-fx function to register an effect handler which returns an effects map (as opposed to reg-event-db which only returns db). Your effects map can be empty, and doesn't need to return a db. See Effects for more info on this.
You could rewrite your event as:
(reg-event-fx
:init-link-viewer
(fn [db [_ highlights]]
(utils/load-highlights highlights)
(utils/init-selection)
{}))
However you may want to take this further, and return your side effects as data. This means that your event handlers are easily testable, and decouples the event from it's side effects. This will mean that you need to write and register effects handlers as well. This could look something like:
(reg-event-fx
:init-link-viewer
(fn [db [_ highlights]]
{:load-highlights highlights
:init-selection true}))

Related

Making an atom of a subscription requires derefing twice. Problem only occurs when using defonce

When I use def to save an atom, it works as expected. But when I use defonce, I have to deref twice: ##my-state. I want to use defonce because I want state preserved during reloads.
This works as expected
(def my-state (reagent/atom (re-frame/subscribe [::subs/photos])))
This requires two derefs to access the values
(defonce my-state (reagent/atom (re-frame/subscribe [::subs/photos])))
Subscription code
(re-frame/reg-sub
::photos
(fn [db [_]]
(:photos db)))
I want to use defonce because I want state preserved during reloads.
Then just don't use Reagent's atoms, use re-frame's subscriptions instead. They derive their values from re-frame's app-db which is itself defined with defonce.

Using an anonymous Js function in a go block

I'm attempting to do some timed animation in clojurescript/reagent and I'm trying to use core.async to achieve series of timed steps in order. I'm using a third party js react library, so, to call its functions I'm using the form (fn [] ^js (.function (.something #ref)). However putting this anonymous function inside the go block as follows doesn't work -
(go
(js/console.log "going")
(<! (timeout 3000))
(fn [] ^js (.function (.somedata #lib))
(js/console.log "landed")
)
This returns "going" and "landed" timed correctly and works when putting another console.log function in its place. However if you wrap this console.log in an Fn it no longer gets called. It is being called in the :on-click handler of a component. What have I missed?
That ^js there is unnecessary.
When you wrap something in (fn [] ...), that something is not called unless that fn is called. I.e. ((fn [] ...)). But then, you end up creating a function and calling it immediately, which is completely unnecessary.
So, assuming I understand you correctly, you can simply replace that (fn [] ^js ...) with (-> #lib .somedata .function).
On a side note, somedata sounds like it's just a field that has some data and not a function that needs to be called. If that's the case, use .-somedata instead of .somedata.
As mentioned by Eugene Pakhomov using (fn [] ...) only creates a function, it does not call it. Thus it it basically just elimnated entirely without doing anything.
Your motiviation here seems to get rid of the inference warning. So the underlying problem is that core.async is rather forgetful when in comes to type hints. If you ask me you shouldn't do any interop in go blocks at all and rather move it all out. Either via defn or local function outside the go.
(defn do-something []
(.function (.somedata ^js #lib)))
(go
(js/console.log "going")
(<! (timeout 3000))
(do-something)
(js/console.log "landed"))
(let [do-something (fn [] (.function (.somedata ^js #lib)))]
(go
(js/console.log "going")
(<! (timeout 3000))
(do-something)
(js/console.log "landed")))
Also, just a word of caution. Using core.async for this will substantially increase the amount of code generated for code in go blocks. If you really need to do is delay something use (js/setTimeout do-something 3000). Use go with caution, it'll easily generate 10x the code for some things than would normally be required.

Why need to return a function in Reagent component?

From the Reagent introduction, a simple timer component:
(defn timer-component []
(let [seconds-elapsed (r/atom 0)]
(fn []
(js/setTimeout #(swap! seconds-elapsed inc) 1000)
[:div
"Seconds Elapsed: " #seconds-elapsed])))
and below it reads
The previous example also uses another feature of Reagent: a component
function can return another function, that is used to do the actual
rendering. This function is called with the same arguments as the
first one.
This allows you to perform some setup of newly created components
without resorting to React’s lifecycle events.
Can someone remind me of the underlying principle here? Why do we need this anonymous function? Why not just
(defn timer-component []
(let [seconds-elapsed (r/atom 0)]
(js/setTimeout #(swap! seconds-elapsed inc) 1000)
[:div
"Seconds Elapsed: " #seconds-elapsed])))
From what I remember, Reagent calls timer-component every time it wants to render - potentially setting up the same piece of state (seconds-elapsed) over and over again.
By returning that anonymous function instead, it tells Reagent "use this to render timer-component". This way your state setup is separated from rendering, and like your doco quote says, its a way to perform state setup without using Reacts lifecycle events.
Hope that makes sense
Tl;dr: The anonymous function that is returned is the render method, which every component must have. You can elide the anonymous function if you use the with-let macro in Reagent.
The indispensable part of a React component is a render function, which takes a single object argument and returns a React element. The difference between render
and the component constructor is that, while both methods are called upon construction, render is called on each update. (For instance, if someone calls the setState method of the component).
In the above example, the difference between the inner, anonymous function and the outer timer-component function is the same as between render and the constructor. Notice that the anonymous function closes over the variables bound in the let clause, which allows it to be stateful. If timer-component itself were the render function, then it would be called on every update, and seconds-elapsed would be endlessly reset to zero.
See the doc on the Reagent repo called "Creating Reagent Components".

Subscribe and add-watch in uberjar

I have component created with reagent/create-class which gets atom created by subscribe. I am adding a watch on :component-did-mount in order to call component (js) function on request, which is triggered by change in the atom (there is a server round trip). It looks somewhat as following:
(defn editor [text issue-hints]
(let []
(reagent-core/create-class
{:component-did-mount
#(let [editor (js/SimpleMDE.
(clj->js {...}))]
(do
...
(add-watch issue-hints :watch-issue-hints (show-hint (-> editor .-codemirror)))
...))
:reagent-render
(fn [this] [:textarea])})))
(defn edit-panel [text]
(let [test (re-frame.core/subscribe [:issue-hints])]
[box
:class "issue-detail"
:size "auto"
:child [:div.issue-detail [editor text test]]]))
It works well when debugging the project, but once uberjar file is run, watch handler never gets called. What is the most strange thing to me is that if at least dummy reference to subscription atom is added, it works well again (eg. dummy #issue-hints in same let as subscription). Server round trip looks good.
Can someone give me explanation and/or suggestion for more reasonable fix/workaround?
It looks like you need two params in :reagent-render, not one -
:reagent-render
(fn [text issue-hints] [:textarea])}))) ---> Not "this", but should match initial args
When you only pass one arg, and it is not derefed in the component-did-mount fn, it won't receive the subscription on subsequent changes.
Further, I don't think that you need to explicitly use add-watch, as that is what the re-frame subscription is giving you ootb. By using the deref syntax #issue-hints, the element will be notified any time a change happens to issue-hints, and you should be able to watch the state from the app-db.
If you add the 2nd arg, my guess is that you could drop the add-watch and it should work as expected.
Here are the docs and if you look at the code sample, you see the repetition of the args...
----- Edit: Will Form-2 work? -----
(defn editor [text issue-hints]
(let [hints #issue-hints
editor (js/SimpleMDE. (clj->js {...})] ;;-> This will not be dynamic, so consider moving to returned fn if necessary
(fn [text issue-hints]
(if hints
[:textarea (special-hint-handler hints)]
[:textarea]
))))
So based on the comments, this would give you a watcher on issue-hints, and you could respond accordingly. The subscription does not necessarily need to be used on the DOM.

How to call re-frame.core/dispatch and re-frame.core/subscribe in same event handler

For example:
(defn starrating []
(reagent/create-class
{:reagent-render
(fn []
[:div
[:input {:type "checkbox"
:on-click #(do (re-frame/dispatch
[:set-star-rating
(-> % .-target .-checked)])
(get-data-from-server))}]])}))
(defn get-data-from-server []
(let [star (re-frame/subscribe [:star-rating])]
(ajax/GET (str "http://192.168.0.117:8080/json/searchhotels.json"
"?star=" #star)
{:response-format :json
:keywords? true
:handler success-handler
:error-handler error-handler})))
In the above example the checkbox is not set.
When the checkbox is ticked, the star variable is set to true
But after this, when we call subscribe to get the value in star it is returning previous value i.e false
It will call: http://192.168.0.117:8080/json/searchhotels.json?star=false
When you un-check the checkbox, the request becomes
http://192.168.0.117:8080/json/searchhotels.json?star=true
Why re-frame.core/subscribe is returning previous set value?
re-frame has a data cycle: db -> subscriptions -> view -> dispatch events -> db. That's the most important thing to understand here.
Try setting your checkbox value in starrating with a subscription from app-db, so that the data flows from app-db into your view.
Also try putting get-data-from-server inside an event handler, so that your view is not handling all of the mechanics of querying, but rather is just dispatching events, without the knowledge of what needs to happen to respond to them.
There's a bunch of good documentation on this at https://github.com/Day8/re-frame/tree/master/docs
Subscriptions are reactions meant to be use with reagent components.
Dispatch is asynchronous. Use dispatch-sync if you want it synchronous.
Look into https://github.com/Day8/re-frame-http-fx to make ajax calls while keeping your event handlers as pure functions.
Read the docs, re-frame has very good documentation. Readme.md in github. Have a look at example apps in the repository for examples.