re-frame Subscriptions Got Even Better

Up until recently, to use re-frame subscriptions in Reagent views, you had to use a form-2 component.

A form-2 component is a function that returns another function, which does the actual rendering of the component to hiccup. In contrast, a form-1 component renders the hiccup directly.

;; form-1
(defn todo-item [todo]
   [todo-checkbox (:id todo) (:completed todo)]
   [:label {:unselectable "on"} title]
   [:button.destroy {:on-click #(dispatch [:todos/remove (:id todo)])}]])

;; form-2
(defn todo-item [todo]
  (fn [todo]
     [todo-checkbox (:id todo) (:completed todo)]
     [:label {:unselectable "on"} title]
     [:button.destroy {:on-click #(dispatch [:todos/remove (:id todo)])}]]))

It’s a small difference, but it has interesting uses. With a form-2 component the outer function is only called once. When re-rendering a component, only the inner function is called. This gives you a place to put one-time initialization code. In that sense it’s a bit like React’s componentWillMount hook.

Since the inner function is a closure, you can have it close over variables by using a let block. A common pattern is to close over a Reagent atom to hold component-local state.

(require '[reagent.core :as r])

(defn todo-input []
  (let [title (r/atom "")]
    (fn []
      [:input#new-todo {:type "text"
                        :value @title                           ;; <------------ deref!
                        :placeholder "What needs to be done?"
                        :auto-focus true
                        :on-change #(reset! title (-> % .-target .-value))}])))

By deref’ing the atom inside the render function Reagent will know that the component depends on this ratom, and re-render it when the atom updates.

The same is true for Reagent reactions, such as returned by re-frame’s subscribe function. You only want the reaction to be created once, but it should be dereferenced for its current value whenever the component re-renders.

The re-frame docs about “subscription flow” contain a great introduction to ratoms and reactions. They are also covered in depth in Lambda Island episode 20, re-frame Subscriptions

(require '[re-frame.core :refer [subscribe])

(defn toggle-all-checkbox []
  (let [all-complete? (subscribe [:todos/all-complete?])]
    (fn []
       [:input {:type "checkbox"
                :checked @all-complete?}]             ;; <---------------- deref!
       [:label {:for "toggle-all"} "Mark all as complete"]])))

Re-frame 0.8 introduced a subscription cache, meaning that multiple calls to subscribe with the same arguments will return the same identical reaction.

In version 0.9 this became official, and so now you can subscribe and dereference a subscription in one go.

(defn toggle-all-checkbox []
   [:input {:type "checkbox"
            :checked @(subscribe [:todos/all-complete?])}]
   [:label {:for "toggle-all"} "Mark all as complete"]])

It’s a neat change, and one that makes re-frame yet again a little bit more user friendly.

You could go one step further by creating a little helper function that subscribes and derefs in one go:

(def deref-subscribe [query-v]
  (deref (subscribe query-v]))

Or if you like it point-free:

(def deref-subscribe (comp deref subscribe))

There was some discussion to add this helper to re-frame itself, but the jury is still out on what to call it. Proposed names include listen, watch, and input-signal.

Personally I started using <sub in my projects, and I’m liking it a lot. It provides a little visual queue as to where the inputs of a component are. I’ve even consider using >evt as an alias for dispatch.

I would perhaps even go one step further and embrace the unicode future by using ⇐ and ⇒, but it seems ClojureScript doesn’t like Unicode identifiers (´•̥̥̥︵•̥̥̥` )

;; sadly doesn't work
;; (def ⇐ (comp deref re-frame.core/subscribe))
;; (def ⇒ re-frame.core/dispatch)

(def <sub (comp deref re-frame.core/subscribe))
(def >evt re-frame.core/dispatch)

(defn toggle-all-checkbox []
   [:input {:type "checkbox"
            :checked (<sub [:todos/all-complete?])
            :on-change #(>evt [:todos/toggle-all])}]
   [:label {:for "toggle-all"} "Mark all as complete"]])

If you’re wondering how you would type those arrows, then it’s about time you set up a Compose Key!

More blog posts

Announcing lambdaisland/uri 1.0.0

I just released lambdaisland/uri, a pure Clojure/ClojureScript URI library. It is available on Github and Clojars.

This is a small piece of the code base that powers It’s inspired by Ruby’s Addressable::URI, the most solid URI implementation I’ve seen to date, although it only offers a small part of the functionality that library offers.

It’s written in pure Clojure/ClojureScript, with only minimal use of .cljc reader conditionals to smooth over differences in regular expression syntax, and differences in core protocols. It does not rely on any URI functionality offered by the host, such as, so it’s usable across all current and future Clojure implementations (Clojure, ClojureScript, ClojureCLR).

Game Development with Clojure/ClojureScript

This weekend it’s Ludum Dare again, the world’s longest running game jam. The idea is that, alone or with a team, you build a game in a weekend based on a certain theme.

We got a little team together here in Berlin, and so I’ve been reviewing what options there are for someone wanting to build a game in Clojure or Clojurescript.

The good news is there are plenty of options, as you’ll see from the list below. You can do desktop games, browser based games with canvas or webgl, and you can even create Unity 3D games, all from your comfortable Clojure parentheses.

Union Types with Clojure.Spec

Elm and other statically typed languages have a great feature called Union Types (also called Sum Types or Algebraic Data Types).

Here’s an example taken from Elm. Suppose your system used to represent users as integers, maybe just an auto-incrementing primary key, but then switched to UUIDs represented as strings.

To correctly model this situation, you need a way to create a type that can be either an integer or a string, that’s what union types give you.