Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing re-frame events that do not change app-db

There are certain events that do not result in app-db changing. They only change the dom, e.g: init a custom scroll, getting the selected text, etc. How should I deal with them in re-frame, since the event handler requires to return a new app-db? I am getting around by returning the existing db, but it does not seem right. Is there a better way to do it? A few of my handlers look like this:

 (re-frame/reg-event-db
    :init-link-viewer
    (fn [db [_ highlights]]
      (utils/load-highlights highlights)
      (utils/init-selection)
      db))
like image 301
Chin365 Avatar asked Oct 19 '16 06:10

Chin365


1 Answers

You can use the reg-event-fx function to register an effect handler which returns an effects map (as opposed to reg-event-db which only returns db). Your effects map can be empty, and doesn't need to return a db. See Effects for more info on this.

You could rewrite your event as:

(reg-event-fx
  :init-link-viewer
  (fn [db [_ highlights]]
    (utils/load-highlights highlights)
    (utils/init-selection)
    {}))

However you may want to take this further, and return your side effects as data. This means that your event handlers are easily testable, and decouples the event from it's side effects. This will mean that you need to write and register effects handlers as well. This could look something like:

(reg-event-fx
  :init-link-viewer
  (fn [db [_ highlights]]
    {:load-highlights highlights
     :init-selection true}))
like image 127
Daniel Compton Avatar answered Jan 04 '23 00:01

Daniel Compton