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]
  [:div.view
   [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]
    [:div.view
     [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 []
      [:span
       [: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 []
  [:span
   [: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 []
  [:span
   [: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!

About the author

Arne divides his time between making Clojure tutorial videos for Lambda Island, and working on open-source projects like Chestnut. He is also available for Clojure and ClojureScript training and mentoring. You can support Arne through his Patreon page.

More blog posts

Clojure Gotchas: Surrogate Pairs

tl;dr: both Java and JavaScript have trouble dealing with unicode characters from Supplementary Planes, like emoji 😱💣.

Today I started working on the next feature of lambdaisland/uri, URI normalization. I worked test-first, you’ll get to see how that went in the next Lambda Island episode.

One of the design goals for this library is to have 100% parity between Clojure and ClojureScript. Learn once, use anywhere. The code is all written in .cljc files, so it can be treated as either Clojure or ClojureScript. Only where necessary am I using a small amount of reader conditionals.

Simple and Happy; is Clojure dying, and what has Ruby got to do with it?

The past week or so a lot of discussion and introspection has been happening in the Clojure community. Eric Normand responded to my one year Lambda Island post with some reflections on the size and growth of the community.

And then Zack Maril lamented on Twitter: “I’m calling it, clojure’s dying more than it is growing”. This sparked a mega-thread, which was still raging four days later. A parallel discussion thread formed on Reddit. Someone asked if their were any Clojure failure stories. They were pointed at this talk from RubyConf 2016, which seemed to hit a lot of people right in the feels, and sparked a subthread with a life of its own.

Meanwhile Ray, one of the hosts of the defn podcast reacted to the original tweet: “I’m calling it: Clojure is alive and well with excellent defaults for productive and sustainable software development.” This sparked another big thread.

Loading Clojure Libraries Directly From Github

Did you ever fix a bug in an open source library, and then had to wait until the maintainer released an updated version?

It’s happened to me many times, the latest one being Toucan. I had run into a limitation, and found out that there was already an open ticket. It wasn’t a big change so I decided to dive in and address it. Just a little yak shave so I could get on with my life.

Now this pull request needs to be reviewed, and merged, and eventually be released to Clojars, but ain’t nobody got time for that stuff. No sir-ee.

Lambda Island Turns One, The Story of a Rocky Ride

One year ago to date I launched Lambda Island, a service that offers high quality video tutorials on web development with Clojure and ClojureScript. It’s been quite a ride. In this post I want to look back at the past year, provide some insight into how this experience has been for me, and give you a glimpse of what the future has in store.

This story really starts in December 2015. After three years of doing contract work for Ticketsolve I decided it was time for a change. I have been self-employed for many years, but I knew that sooner or later I wanted to try my hand at selling a product, rather than selling my time.

In January and February I took some time for soul-searching, and recharging. I went to speak at RubyConf Australia, and got to hang out with some old friends around Australia and New Zealand. Once back in Berlin I got busy creating Lambda Island.

Writing Node.js scripts with ClojureScript

In the two most recent  Lambda Island episodes I covered in-depth how to create command line utilities based on Lumo, how to combine them with third party libraries, and how to deploy them to npmjs.com.

However there’s a different way to create tools with ClojureScript and distribute them through NPM, without relying on Lumo. In this blog post I want to quickly demostrate how to do just that.

To recap, Lumo is a ClojureScript environment based on Node.js, using bootstrapped (self-hosted) ClojureScript. This means the ClojureScript compiler, which is written in Clojure and runs on the JVM, is used to compile itself to JavaScript. This way the JVM is no longer needed, all you need is a JavaScript runtime to compile and run ClojureScript code, which in this case is provided by Node.js. On top of that Lumo uses nexe, so Lumo can be distributed as a single compact and fast executable binary.

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 lambdaisland.com. 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 java.net.URL, 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.