This episode is for subscribers only. Sign Up or Log in to watch it.

20. re-frame Subscriptions

Published 17 November 16

A complete look at re-frame subscriptions, including coverage of Reagent's atoms and reactions. You learn how to write subscriptions, how they work, and how to plug them together into a signal graph.

Show notes

In re-frame, views receive data from the database through subscriptions. Suppose we have a database that looks like this, here we’re building a todo list app, and individual todo items are represented as hash-maps, bundled together in a vector under the :todos key.

(def default-db
  {:todos [{:id (random-uuid)
            :title "Donate to charity"
            :completed false}]})

We want to use this information to render a list of all todos that haven’t been completed yet. So we need a subscription, let’s call it :visible-todos.

Registering a subscription is done with re-frame.core/reg-sub. You first pass it the name of the subscription as a keyword, followed by the function that gets the right data from the database.

This function receives the current state of the application database, and pulls out the list todos that haven’t been completed yet. You can think of it as a database query.

This subscription function also receives a second argument, the query vector. This is useful for subscriptions that take arguments, we’ll see examples of those later on.

(re-frame.core/reg-sub :visible-todos
         (fn [db query-v]
           (remove :completed (:todos db))))

browse source code

Starting point is the ep20-start branch, the episode goes up to the ep20-end. [Full diff]

Errata

The video is missing the definition of the :display-type subscription. The transcript has been updated to include it.

(reg-sub :display-type
         (fn [db _]
           (:display-type db)))

Prerequisites

This episode is part of a series on building React apps using Reagent and re-frame.