Fork me on GitHub
#re-frame
<
2022-04-27
>
Pablo19:04:24

Hello What is the idiomatic way to get the current date/time on a subscription? :thinking_face: On an event it would be a coeffect, but what is its counterpart on subscriptions?

p-himik19:04:42

There's no counterpart because subscriptions react to the changes in app-db, and current date/time has nothing to do with app-db. A common solution is to set up a timer with the desired granularity in some effect, fire off that effect in some initializing event, and make that timer write the current date/time under some path in app-db. Then you'll be able to use that value in subscriptions.

lispers-anonymous19:04:35

You could setup a timer in a new reg-sub-raw subscription and wire it up in a form-3 subscription. Something like this (I didn't test it)

(rf/reg-sub-raw
  ::now
  (fn [_ [_ frequency-ms]]
    (let [now (r/atom (js/Date.))
          interval (js/setInterval #(reset! now (js/Date.)) frequency-ms)]
      (reagent.ratom/make-reaction
        #(deref now)
        :on-dispose #(js/clearInterval interval)))))

lispers-anonymous19:04:28

It will re-render your subscription, and whatever views subscribe to it every frequency-ms , so be careful

p-himik20:04:33

Note however that such an approach has been explicitly described as not recommended in re-frame docs.

Pablo20:04:58

Yep, I read https://github.com/day8/re-frame/blob/master/docs/Subscribing-To-External-Data.md but I was left with doubts on how to solve it without leaving the re-frame recommendations. I don’t really need date/time to be reactive, so maybe I will ended up with:

(rf/reg-sub
 ::valid?
 :<- [::deadline]
 (fn [deadline _]
   (< (time/now) deadline)))
But I was looking for some way to make that function pure

p-himik20:04:07

The simplest way to achieve that would be to pass now from a view. As far as I'm aware, the next simplest way that's still within the framework of re-frame recommendations is the approach I described above.

Pablo20:04:40

Thanks 🙂

Ted Ciafardini22:04:32

Going through the documentation -it’s not entirely clear what the difference between reg-fx and reg-event-fx Is it just that the handler within reg-fx does not implicitly receive the cofx map - but rather whatever values you hand to it? While reg-event-fx takes cofx no matter what followed by the event?

Ted Ciafardini22:04:54

I may have just rubber ducked myself but would appreciate confirmation lol

lispers-anonymous22:04:39

In reg-event-fx handlers you are expected to return a map with keys of effects. Each of those keys corresponds to a handler registered with reg-fx

thanks2 1
Ted Ciafardini22:04:14

I see. :db new-db-value That explains the explanation that :db is an effect registered by re-frame out of the box

Pablo23:04:07

Yep, reg-event-fx declares a new event, that is supposed to return a map of effects (that are declared with reg-fx)

👍 1