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

25. re-frame Events and Effects

Published 20 February 17

Side effects in re-frame are handled through events. You’ll implement several event handlers of a TodoMVC app so it becomes functional. You’ll also implement custom effect and co-effect handlers for storing the application state in localStorage. To debug event handlers you’ll learn about the “debug” interceptor, and about re-frisk, a handy tool for inspecting your re-frame database.

Show notes

In this episode you’ll learn all about re-frame event handlers, as well as effects and co-effects. You’ll continue building the “redolist” app from previous episodes, a TodoMVC implementation based on re-frame. All code is on Github, you can find a link in the show notes. The starting point for this episode is the ep25-start branch.

So grab the repo, switch to the right branch, and poke around in it a bit before continuing this episode. All the views are already there, since they were covered in previous episodes, and they receive data from the database through subscriptions.

The file with event handlers is still mostly empty, you’ll be adding more of them soon.

Before continuing, I recommend adding re-frisk, a helpful tool for inspecting the state of your re-frame app. First add it to project.clj. It’s currently at version 0.3.2.

;; project.clj
:dependencies [,,,
               [re-frisk "0.3.2"]]

In core.cljs, after requiring it, call enable-re-frisk! in the dev-setup function. That’s all the setup you need.

(ns redolist.core
  (:require ,,,
            [re-frisk.core :refer [enable-re-frisk!]]))

(defn dev-setup []
  (when config/debug?
    (enable-re-frisk!)
    ,,,))

browse source code

The starting point for this episode is the ep25-start branch. To code along at home do

git clone -b ep25-start https://github.com/lambdaisland/redolist.git 

For the usage of <sub, see the blog post about the revamped re-frame subscriptions.

Cheat sheet

;; Events that purely update the database
(reg-event-db :set-user-name
  (fn [db [_ user-name]]                          ;; [old-db-value event-vector] -> new-db-value
    (assoc db :user-name user-name)))

;; Same event handler, but rewritten to use co-effects -> effects
(reg-event-fx :set-user-name
  (fn [cofx [_ user-name]]                        ;; [cofx-map event-vector] -> fx-map
    {:db
     (assoc (:db cofx) :user-name user-name)}))

Built-in co-effects