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

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.

Related

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.

Can i use (if) as a form-2 reagent render-function

I use an (if) condition as form-2 render-function in this way:
(defn bro [dex]
(let [yo (inc dex)]
(if true
[:div (str yo)])))
instead of this way:
(defn bro [dex]
(let [yo (inc dex)]
(fn [dex]
(if true
[:div (str yo)]))))
Is a problem if i use an (if) statement instead of an (fn) function?
And what happens when the statement gone false? The render function returns with nil?
No, this won't work as you expect. To understand the difference, consider the following two components:
(defn test-component-if []
(let [a (atom 1)
_ (.log js/console "let in -if")]
(if (odd? #a)
[:div
[:p "odd"]
[:button {:on-click #(swap! a inc)}
"inc"]]
[:div
[:p "even"]
[:button {:on-click #(swap! a inc)}
"inc"]])))
(defn test-component-fn []
(let [a (atom 1)
_ (.log js/console "let in -fn")]
;; I dub thee test-inner
(fn []
(if (odd? #a)
[:div
[:p "odd"]
[:button {:on-click #(swap! a inc)}
"inc"]]
[:div
[:p "even"]
[:button {:on-click #(swap! a inc)}
"inc"]]))))
test-component-fn works as expected, while test-component-if does not. Why is that? Well when a reagent component can return one of two things (I'm ignoring "type-3" components, as that hooks into react knowledge). It can return
a vector
another function
If it returns a vector, the function itself becomes the render function, in our case test-component-if. When it returns a function, the function that was returned, not the original function, is the render function. In this case, what I have dubbed test-inner
When Reagent calls a render function, it tracks the atoms that function accesses, and whenever that atom changes it calls the render function. So what happens when we use test-component-if?
Reagent calls test-component-if
Our let clause binds a new atom a to 1.
A vector is returned
We click the button
The atom a is incremented
Reagent sees the change to a and calls test-component-if
Our let clause binds a new atom a to 1. (A different atom than our previous a)
Ooops!
So a is always 1. You can verify this by looking at the console, and seeing that the message is printed every time you click the button.
Now how about test-component-fn?
Reagent calls test-component-fn
Our let clause binds a new atom a to 1.
test-component-fn returns test-inner which closes over a
Reagent calls test-inner
We click the button
a is incremented
Reagent sees the change to a and calls test-inner
Repeat as many times as you want.
You can verify that let only gets executed once again on the console. Click the button as many times as you want, the message will only be printed when it's first rendered.
In terms of an if without an else clause, this will indeed return nil. It's convention to use when instead of if in such cases, which makes it clear the lack of an else is intended. It also has the advantage of including an implicit do. As for what Reagent will do when it encounters that nil, in most cases it will silently remove it and display nothing.
Is a problem if i use an (if) statement instead of an (fn) function?
I think you meant to use an if inside an fn function, but either way it's not a problem.
And what happens when the statement gone false? The render function returns with nil?
Reagent handles these gracefully, a nil will be skipped (no corresponding child is created). If you see the TODOs app example in the official docs, you'll see source has code like the following:
(when (pos? done)
[:button#clear-completed {:on-click clear-done}
"Clear completed " done])]))
In this case, if done is not a positive number, the return value of this expression is nil and the button to clear the completed tasks is simply not added to the DOM.

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.

Can name munging be avoided for an interop call in ClojureScript?

In advanced compilation
(js/console.log "HELLO"
js/window.navigator.msSaveBlob
(.. js/window -navigator -msSaveBlob)
(aget js/window "navigator" "msSaveBlob")
js/console.log)
=>
HELLO undefined undefined function function
I think this means that js/console has some provided externs, but navigator does not (or at least not the ms specific stuff).
AFAIK the only way to avoid this is to create some externs? But this seems unnecessarily obtuse; why would you ever want js/anything to be munged?? Wouldn't it make make more sense to never munge js/anything interop?
System functions are not munged; only your own functions are. You probably want (.log js/console ...) ?
For de-munging your own functions, place ^:export between the defn and the function name to export its name intact.
Here is more information.
All see the section called "munging" here.

om get-props vs get-state

I am trying to grasp the purpose of the two OM functions get-state and get-props. Have a look at the following example:
(defn example [app owner]
(reify
om/IInitState
(render-state [this state]
(println "app-state: " app )
(println "state: " state )
(println "get-props: " (om/get-props owner) )
(println "get-state: " (om/get-state owner) )
(dom/div nil "hello"))))
You will notice that app and state contain exactly what get-props and get-state return, which seems at the first glance pretty redundant.
Now, not all the lifecycle functions (e.g. IWillMount ) pass the state argument, so when you need it in such circumstances, it's obvious that you need to invoke om/get-state to get access to it.
However, for the app-state it looks different to me. You always have the app-state cursor available in all functions since it's a top-level argument of the function, even if you need it in callbacks you can just pass it around. Most examples/tutorials make use of get-state but I can't find an example of get-props. Is get-props redundant? Where would I use it?
And one more thing related to this construct. In React we have props and state, but in OM we have app-state and state (internal state) which confused me when learning OM. Props are passed from parent to child in React, likewise in OM we pass app-state (cursors) to children. Are the following observations valid?
app-state is the OM equivalent of React' props
props is React is just data, while app-state in OM is data wrapped in cursors
this means that OM doesn't have props, only app-state cursors, hence the function get-props really means get-app-state
According to the docs, get-props is mostly (or exclusively) needed in the IWillReceiveProps phase. will-receive-props gets a next-props argument, which contains the future app-state/props. get-props gives you the current app-state/props so that you can compare the two.
From the Om docs for IWillReceiveProps:
In your implementation if you wish to detect prop transitions you
must use om.core/get-props to get the previous props. This is
because your component constructor function is called with the
updated props.
So the rest of the time, get-props isn't necessary because, as mentioned in the question, you have access to the cursor.