Skip to content

Step 04: Reagent cursors

Valentin Waeselynck edited this page Sep 5, 2015 · 7 revisions

Browse code - Diff - Live demo

To reset your workspace for this step, run git checkout step-4, then refresh your page.


Let's keep improving our phones list by enabling our users to order the phones by some property. This is similar to what we did in the previous step, but we're going to do it differently, using another feature of Reagent: cursors.

First, we'll add an :order-prop property to our state atom:

(defonce state
  (rg/atom {:phones hardcoded-phones-data
            :search ""
            :order-prop :name
            }))

However, when manipulating this :order-prop property, we won't interact with state directly, but with a cursor of state:

(def order-prop-state (rg/cursor state [:order-prop]))

Reagent cursors are like a view of a small part of an atom; they have the same programming interface as atoms, but manipulating them will only affect the underlying atom on a limited scope. Thus,

@order-prop-state
;; yields the same result as
(get-in @state [:order-prop])

(reset! order-prop-state :age)
;; is equivalent to 
(swap! state assoc :order-prop :age)

What's nice when dealing with a cursor is that you don't have to know, or care, about the structure of the whole state atom, only the part that's of interest to you at the moment. This enables you to limit the responsibility of your components, and gives you the flexibility to change the structure of the state atom.

We'll define a component to select the order property we want:

(defn <order-prop-select> []
  [:select {:value @order-prop-state
            :on-change #(reset! order-prop-state (-> % .-target .-value keyword))}
   [:option {:value :name} "Alphabetical"]
   [:option {:value :age} "Newest"]
   ])

As you can see, we use order-prop-state exactly as it it were a regular atom (for all order-prop-select knows, it could be one).

Now let's modify slightly our phones-list component to display the sorted list of phones, conveniently using clojure.core/sort-by:

(defn <phones-list> "An unordered list of phones"
  [phones-list search order-prop]
  [:ul.phones
   (for [phone (->> phones-list 
                 (filter #(matches-search? search %))
                 (sort-by order-prop))]
     ^{:key (:name phone)} [<phone-item> phone]
     )])

All that's left to do is to reflect these changes in top-cpnt:

(defn <top-cpnt> []
  (let [{:keys [phones search]} @state]
    [:div.container-fluid
     [:div.row
      [:div.col-md-2
       [<search-cpnt> search]
       [:br]
       "Sort by:"
       [<order-prop-select>]]
      [:div.col-md-8 [<phones-list> phones search @order-prop-state]]
      ]]))

Summary

Reagent cursors can help decouple components from your application state, by making them operate on a restricted scope of the underlying ratom.

In the next step, we'll see how to use AJAX in our app.

Clone this wiki locally