I am new to Clojure and Reagent. Kindly tell how to print the variable first inside the atom variable contacts?
(def app-state (r/atom {:contacts [{:first "Ben" :last "Lem" :middle "Ab"}]}))
I am new to Clojure and Reagent. Kindly tell how to print the variable first inside the atom variable contacts?
(def app-state (r/atom {:contacts [{:first "Ben" :last "Lem" :middle "Ab"}]}))
First of all: the reagent tutorial is a really good place to start. It even gives you examples to solve exactly this problem.
Since reagents atom
can be treated just as a regular Clojurescript atom, you can use all your normal sequence operations. Keep in mind that in order to access the current value, you have to dereference the atom via @
.If you really just want to access the first :first
in your atom:
(:first (first (:contacts @app-state)))
or (get (first (get @app-state :contacts)) :first)
Or, if you think it's more readable
(-> @app-state
:contacts
first
:first)
I guess what you might want to do is define a few functions to make the access more easy such as:
(defn get-contacts!
"Returns the current vector of contacts stored in the app-state."
[]
(:contacts @app-state))
(defn get-first-names!
"Return a vector of all first names in the current list of contacts in the
app-state."
[]
(mapv :first (get-contacts!)))
Please keep in mind that in reagent (and in general really) you might want to dereference that atom as fiew times as possible, so look for a good place to dereference it and just use regular functions that operate on a simple sequence instead of an atom.
Still, I would really suggest you go read the aforementioned reagent tutorial.
Here is a concise way to access the value that you are looking for using Clojure's (get-in m ks) function:
(get-in @app-state [:contacts 0 :first])
Just as an extra, you may see this often written as
(->> @app-state
:contacts
(mapv :first)
first
and it's useful to understand what's going on here.
->>
is a macro called thread-last which will re-write the code above to be
(first (mapv :first (:contacts @app-state)))
Thread last is a bit weird at first but it makes the code more readable when lots of things are going on. I suggest that on top of the reagent tutorial mentioned in the other comments, you read this.
@app-state
will give you whatever is inside the r/atom and (:first (first (:contacts @app-state)))
will return the first element and (println (:first (first (:contacts @app-state))))
will print output to the browser console (so you need to have the developer tools console open to see it).
Note that for println
to output to the browser developer tools console you need to have this line in your code:
(enable-console-print!)