Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between reg-event-db, reg-event-fx and reg-event-ctx in Re-frame?

There are 3 event fns in Re-frame, I can do the same thing with both reg-event-db and reg-event-fx.

What is the main difference between reg-event-db, reg-event-fx and reg-event-ctx?

When should I use reg-event-fx over reg-event-db or vice versa.

like image 635
Ertuğrul Çetin Avatar asked Feb 25 '19 10:02

Ertuğrul Çetin


1 Answers

Short answer: they represent three levels of abstraction for registering event handlers.

reg-event-db is a more focused, limited version of reg-event-fx. When your handler is only concerned with the db value, then reg-event-db is the most convenient to use; you could write the same handler with reg-event-fx but you'd have to get the :db value out of the handler's input. This is the most common case for registering event handlers.

If your handler needs to access co-effects/produce effects then you'd use reg-event-fx and get the :coeffects value (and :db if necessary) from the handler's input. A common use case is when you need to access browser storage (e.g. cookies, local storage) but want to keep your handlers free of side-effects. The docs have an example of this.

reg-event-ctx is an even lower-level type of event handler which receives the entire context, but this is rarely what you'd want to use to register an event handler. From the docs: This form of registration is almost never used.

This is an example context map:

{:coeffects {:event [:some-id :some-param]
             :db    <original contents of app-db>}

 :effects   {:db    <new value for app-db>
             :dispatch  [:an-event-id :param1]}

 :queue     <a collection of further interceptors>
 :stack     <a collection of interceptors already walked>}
  • reg-event-db handlers are only given :coeffects -> :db value, and their return value informs :effects -> :db
  • reg-event-fx handlers are given the entire :coeffects value, and their return value informs :effects
  • reg-event-ctx handlers are passed (and return) this entire context map
like image 188
Taylor Wood Avatar answered Oct 18 '22 00:10

Taylor Wood