Fork me on GitHub
#re-frame
<
2019-05-09
>
fmnoise15:05:45

Hi everyone. Is that ok to use subscription in event handler?

fmnoise15:05:14

like

(rf/reg-event-fx ::submit-order
  (fn [_ _]
    (if @(rf/subscribe [:admin?]) ...

robcorp16:05:52

@fmnoise @manutter51 Why not just get what you need out of the db?

manutter5116:05:58

Not all subscriptions are in the db — you can derive calculated values from other subscriptions, and you may not want to duplicate the code.

manutter5117:05:29

That said, it takes a bit of extra effort to get subscription data safely into the event handler, so for simple (non-derived) subscriptions, it’s usually simpler and easier to just pull it out of the app-db.

fmnoise17:05:33

yep, it's in db, but getting that from db smells a bit, cause if db path changed than we need to update that in 2(or more) places which pushes us to idea of storing and sharing subscription path like [:user :role :admin?] and using it in reg-sub and some other place to get value when subscribe is not suitable

fmnoise17:05:30

I do that some time, but would be good to stick with 1 abstraction to get data

robcorp17:05:22

Ah, I haven't used any subs that don't get their data from the db, so hadn't thought of that use-case.

manutter5117:05:34

The way I get around path changes is with helper functions and organized namespaces. So, for example, I’ll have a namespace that deals with manipulating user data, and at the top I’ll have

(defn user-path [& sub-path] 
  (vec (concat [:user] sub-path)))
and then in a handler I can do (get-in db (user-path :roles :admin?)), which is still readable and simple. And if I decide to make :user a sub-key under :globals, all I have to do is modify user-path to be
(defn user-path [& sub-path]
  (vec (concat [:globals :user] sub-path)))
`