Checkbox in Luminus - clojure

I started to learn Clojure this week, specifically I'm learning web development with Luminus. Since I want to understand the CRUD process, I setup a function to save my post into the DB:
(defn save-post! [{:keys [params]}]
(if-let [errors (validate-post params)]
(-> (response/found "/posts")
(assoc :flash (assoc params :errors errors)))
(do
(db/save-post!
(assoc params :created_at (java.util.Date.)))
(response/found "/posts"))))
The query is pretty basic:
-- :name save-post! :! :n
-- :doc creates a new post record
INSERT INTO posts
(title, body, active, created_at)
VALUES (:title, :body, :active, :created_at)
but the HTML form has a checkbox field:
<input type="checkbox" name="active" value="1">Published<br />
and when it is not selected, the field is not send and the SQL insert query sends the error message "No active field". How can I check if the element "active" is set and add it to "params" as true or false?
Something like:
(assoc params :active (if (nil? params/active) false true))
after the ":created_at (java.util.Date.)" line.

How can I check if the element "active" is set and add it to "params" as true or false?
Looks like your code isn't far from working. You'll need to check the params map to see if it has the checkbox's value. If (:active params) is equal to "1" when the checkbox is checked, then you might do something like this:
(assoc params :active (= "1" (:active params)))
But what this is really trying to do is update a particular value in the map, which can be done more idiomatically:
(update params :active #(= "1" %))
Where the final argument is a function that takes any current value of the keyword and returns the new value.
Another potential gotcha: you may not want to use the params map as direct input to your DB query, because it could very easily contain keys/values that you don't want or expect. It'd be safer to pull only the values you need from it explicitly e.g. (select-keys params [:title :body :active]).
(def params {:active "1", :admin true}) ;; wouldn't want admin to leak through!
(-> params
(select-keys [:title :body :active])
(assoc :created_at (java.util.Date.))
(update :active #(= "1" %)))
;;=> {:active true, :created_at #inst "2017-10-09T20:16:06.167-00:00"}

Related

Getting error Uncaught Error: Assert failed: Reaction is read only; on-set is not allowed

I am new to clojure and reagent. I was trying to generate dynamic number of checkboxes, the state of which is stored in the app state which is a list of dicts like this
[{:checked false, :text "Sample text 1"} {:checked false, :text "Sample text 2"} {:checked false, :text "Sample text 3"}]
The function below is expected to generate a checkbox corresponding to the specified index of app's db (db). The function does it jobs and the checkboxes are clickable.
(defn gen-checkbox [index db]
[re-com/checkbox
:label (:text (#db index))
:model (:checked (#db index))
:on-change #(swap! db assoc-in [index :checked] (not(:checked (#db index))))
])
However, I get this error in the browser console when I click on any checkbox.
Uncaught Error: Assert failed: Reaction is read only; on-set is not allowed
The error occurs at swap!. Can some one point out what I am doing wrong?
The db initialization part is as below:
(re-frame/reg-event-db ::initialize-db
(fn [_ _]
(atom [{:checked false :text "Sample text"}, {:checked false :text "Sample text"}, {:checked false :text "Sample text"}])
))
I also have a function to retreive the db. I am currently getting
(re-frame/reg-sub ::getdb
(fn [db]
#db
))
Based on the tags of your question, I presume that you are using re-frame.
You can't update the database in re-frame directly. Instead, you should register an event handler that updates the database, like the below (the exact code depends on the structure of your DB):
;; (require '[re-frame.core :as rf])
(rf/reg-event-db
:toggle-checkbox
(fn [db [_ index]]
(update-in db [index :checked] not)))
And then dispatch the event in the code of your checkbox's renderer:
...
:on-change #(rf/dispatch [:toggle-checkbox index])
...

Add data in Firestore with Clojure

I am new to the Firestore and Clojure.
Below is my code, Get returns the correct data, however, Set is not successful, without any exception or response.
(defn database-instance
[]
(FirestoreClient/getFirestore))
(def user (java.util.HashMap. {"age" 50
"name" "Josh"
"user_id" "user02"}))
(defn get-credit-detail!
[msg]
(def result
(-> (database-instance)
(.collection "credits")
(.document "document")
(.get)
(.get)
))
(println (.getData result))
;; this Set does not work
(-> (database-instance)
(.collection "credits")
(.document "document1")
(.set user)
)
)
Can you help me with the Set to be able to add new data to firestore?
Thanks!
A little late to answer this but what you have should work. I tried it through the REPL and verified the set worked from the firebase console. Note that you can use a Clojure map with String keys as input without having to resort to creating a java.util.Map.
(-> (database-instance)
(.collection "credits")
(.document "document1")
(.set {"age" 50 "name" "Josh" "user_id" "user02"}))

How do I loop through a subscribed collection in re-frame and display the data as a list-item?

Consider the following clojurescript code where the specter, reagent and re-frame frameworks are used, an external React.js grid component is used as a view component.
In db.cls :
(def default-db
{:cats [{:id 0 :data {:text "ROOT" :test 17} :prev nil :par nil}
{:id 1 :data {:text "Objects" :test 27} :prev nil :par 0}
{:id 2 :data {:text "Version" :test 37} :prev nil :par 1}
{:id 3 :data {:text "X1" :test 47} :prev nil :par 2}]})
In subs.cls
(register-sub
:cats
(fn [db]
(reaction
(select [ALL :data] (t/tree-visitor (get #db :cats))))))
result from select:
[{:text "ROOT", :test 17}
{:text "Objects", :test 27}
{:text "Version", :test 37}
{:text "X1", :test 47}]
In views.cls
(defn categorymanager []
(let [cats (re-frame/subscribe [:cats])]
[:> Reactable.Table
{:data (clj->js #cats)}]))
The code above works as expected.
Instead of displaying the data with the react.js component I want to go through each of the maps in the :cats vector and display the :text items in html ul / li.
I started as follows:
(defn categorymanager2 []
(let [cats (re-frame/subscribe [:cats])]
[:div
[:ul
(for [category #cats]
;;--- How to continue here ?? ---
)
))
Expected output:
ROOT
Objects
Version
X1
How do I loop through a subscribed collection in re-frame and display the data as a list-item? ( = question for title ).
First, be clear why you use key...
Supplying a key for each item in a list is useful when that list is quite dynamic - when new list items are being regularly added and removed, especially if that list is long, and the items are being added/removed near the top of the list.
keys can deliver big performance gains, because they allow React to more efficiently redraw these changeable lists. Or, more accurately, it allows React to avoid redrawing items which have the same key as last time, and which haven't changed, and which have simply shuffled up or down.
Second, be clear what you should do if the list is quite static (it does not change all the time) OR if there is no unique value associated with each item...
Don't use :key at all. Instead, use into like this:
(defn categorymanager []
(let [cats (re-frame/subscribe [:cats])]
(fn []
[:div
(into [:ul] (map #(vector :li (:text %)) #cats))])))
Notice what has happened here. The list provided by the map is folded into the [:ul] vector. At the end of it, no list in sight. Just nested vectors.
You only get warnings about missing keys when you embed a list into hiccup. Above there is no embedded list, just vectors.
Third, if your list really is dynamic...
Add a unique key to each item (unique amoung siblings). In the example given, the :text itself is a good enough key (I assume it is unique):
(defn categorymanager []
(let [cats (re-frame/subscribe [:cats])]
(fn []
[:div
[:ul (map #(vector :li {:key (:text %)} (:text %)) #cats)]])))
That map will result in a list which is the 1st parameter to the [:ul]. When Reagent/React sees that list it will want to see keys on each item (remember lists are different to vectors in Reagent hiccup) and will print warnings to console were keys to be missing.
So we need to add a key to each item of the list. In the code above we aren't adding :key via metadata (although you can do it that way if you want), and instead we are supplying the key via the 1st parameter (of the [:li]), which normally also carries style data.
Finally - part 1 DO NOT use map-indexed as is suggested in another answer.
key should be a unique value associated with each item. Attaching some arb integer does nothing useful - well, it does get rid of the warnings in the console, but you should use the into technique above if that's all you want.
Finally - part 2 there is no difference between map and for in this context.
They both result in a list. If that list has keys then no warning. But if keys are missing, then lots of warnings. But how the list was created doesn't come into it.
So, this for version is pretty much the same as the map version. Some may prefer it:
(defn categorymanager []
(let [cats (re-frame/subscribe [:cats])]
(fn []
[:div
[:ul (for [i #cats] [:li {:key (:text i)} (:text i)])]])))
Which can also be written using metadata like this:
(defn categorymanager []
(let [cats (re-frame/subscribe [:cats])]
(fn []
[:div
[:ul (for [i #cats] ^{:key (:text i)}[:li (:text i)])]])))
Finally - part 3
mapv is a problem because of this issue:
https://github.com/Day8/re-frame/wiki/Using-%5Bsquare-brackets%5D-instead-of-%28parentheses%29#appendix-2
Edit: For a much more coherent and technically correct explanation of keys and map, see Mike Thompson's answer!
Here's how I would write it:
(defn categorymanager2 []
(let [cats (re-frame/subscribe [:cats])]
(fn []
[:div
[:ul
(map-indexed (fn [n cat] ;;; !!! See https://stackoverflow.com/a/37186230/500207 !!!
^{:key n}
[:li (:text cat)])
#cats)]])))
(defn main-panel []
[:div
[categorymanager2]])
A few points:
See the re-frame readme's Subscribe section, near the end, which says:
subscriptions can only be used in Form-2 components and the subscription must be in the outer setup function and not in the inner render function. So the following is wrong (compare to the correct version above)…
Therefore, your component was ‘wrong’ because it didn't wrap the renderer inside an inner function. The readme has all the details, but in short, not wrapping a component renderer that depends on a subscription inside an inner function is bad because this causes the component to rerender whenever db changes—not what you want! You want the component to only rerender when the subscription changes.
Edit: seriously, see Mike Thompson's answer. For whatever reason, I prefer using map to create a seq of Hiccup tags. You could use a for loop also, but the critical point is that each [:li] Hiccup vector needs a :key entry in its meta-data, which I add here by using the current category's index in the #cats vector. If you don't have a :key, React will complain in the Dev Console. Note that this key should somehow uniquely tie this element of #cats to this tag: if the cats subscription changes and gets shuffled around, the result might not be what you expect because I just used this very simple key. If you can guarantee that category names will be unique, you can just use the :test value, or the :test value, or something else. The point is, the key must be unique and must uniquely identify this element.
(N.B.: don't try and use mapv to make a vector of Hiccup tags—re-frame hates that. Must be a seq like what map produces.)
I also included an example main-panel to emphasize that
parent components don't need the subscriptions that their children component need, and that
you should call categorymanager2 component with square-brackets instead of as a function with parens (see Using [] instead of ()).
Here's an ul / li example:
(defn phone-component
[phone]
[:li
[:span (:name #phone)]
[:p (:snippet #phone)]])
(defn phones-component
[]
(let [phones (re-frame/subscribe [:phones])] ; subscribe to the phones value in our db
(fn []
[:ul (for [phone in #phones] ^{:key phone} [phone-component phone] #phones)])))
I grabbed that code from this reframe tutorial.
Also map is preferable to for when using Reagent. There is a technical reason for this, it is just that I don't know what it is.

Check if URL parameter exists in map

(defroutes my-routes
(GET "/:id" [id] (html/display-thing id)))
(def my-map
{:id 1 :title "One"
:id 2 :title "Two"})
Is there a nice way to check if the url parameter id exists in my-map else continue checking if the other routes match? I know you can do something similar with regex like so: ["/:id", :id #"[0-9]+"] and suspect it might be possible to plug in an arbitrary predicate function.
Not actually at a REPL, but isn't this as straightforward as returning nil from html/display-thing if there's no id element in my-map? Take a look at (source GET) to see how the macro passes control to the next route if the method or URL don't match.

Clojure: Hiccup form-handler

I am implementing a simple drop-down using hiccup:
;DATASET/CREATE
(defn get-cols-nms [table]
"This function gets the list of columns of a specific table".
(do (db/cols-list table)))
(defpartial form-dataset [cols-list]
(text-field "dataset_nm" "Input here dataset name")[:br]
(drop-down "table" tables-n)
(submit-button "Refresh")[:br]
(mapcat #(vector (check-box %) % [:br]) cols-list)
)
(defpage "/dataset/create" []
(common/layout
(form-to [:post "/dataset/create"]
(form-dataset (get-cols-nms (first tables-n))))))
(defpage [:post "/dataset/create"] {:as ks}
(common/layout
(let [table (ks :table)]
(form-to [:post "/dataset/create"]
(form-dataset (get-cols-nms table))))))
What I need is to issue a post request (as I think this the only way to do it, but I am open to suggestions) when the drop-down is selected on a specific table (so that "get-cols-nms" gets called with the selected table). In this way, when a table of the database is selected in the drop-down, the table columns will be automatically showed.
So, ultimately, the main point is for me to understand better this function:
(drop-down "table" tables-n)
I think that to do what I want I need the tag to have an "onchange" attribute that calls a javascript function. But I don't know: 1) if I can do this using the hiccup form-helper drop-down; 2) how can I issue (if this is the only solution, maybe there is an hiccup way?) a post request with javascript.
==EDIT==
Following the answer to this question, I rewrote the code above.It should be pretty straightforward. As I think there are not so many examples of hiccup out there, I will post my code here for reference.
Please, bear in mind that there is still a problem with this code: the drop-down won't stay on the selected item, but it will return at the default. This is because it submits "onchange". I still could not find a solution for that, maybe somebody could help...
;DATASET/CREATE
(defn get-cols-nms [table]
(do (db/cols-list table)))
(defpartial form-dataset [cols-list]
(text-field "dataset_nm" "Input here dataset name")[:br]
(assoc-in (drop-down "table" tables-n) [1 :onclick] "this.form.submit()")[:br]
[:input {:type "submit" :value "Submit" :name "name"}][:br]
(mapcat #(vector (check-box %) % [:br]) cols-list)
)
(defpage "/dataset/create" []
(common/layout
(form-to [:post "/dataset/create"]
(form-dataset(get-cols-nms (first tables-n))))))
(defpage [:post "/dataset/create"] {:as ks}
(common/layout
(prn ks)
(let [table (ks :table)]
(form-to [:post "/dataset/create"]
(if (= (:name ks) nil)
(form-dataset (get-cols-nms table))
[:p "It works!"])))))
hiccup.form-helpers/drop-down doesn't directly support adding attributes to its select element, but it does guarantee there is a standard hiccup attribute map in its return value - meaning the attributes are a map at index 1 (the second element) of the returned vector.
That means you can do something like
(assoc-in (drop-down ....) [1 :onchange] "this.form.submit()")
to generate a select tag with an onchange property.