Fork me on GitHub
#re-frame
<
2020-01-10
>
harishtella22:01:13

Hey all, I have been uncertain about this for a while now. Can anyone shed some light? Can I create and deref a re-frame subscription inside a re-frame event handler or not? The FAQ entry below says I should not, but I’m not sure if it is outdated info or not. The alternative methods proposed by the FAQ entry seem a bit annoying to me. I’m curious if the approaches shown in the FAQ are what you all are doing. https://github.com/day8/re-frame/blob/master/docs/FAQs/UseASubscriptionInAnEventHandler.md

isak22:01:38

@harishtella I agree it is annoying. I pass the data in instead

p-himik22:01:08

The entry is not outdated.

harishtella22:01:32

Oh, why didn’t I think of that. As in the reagent component makes the subscription needed, and then passes the value into the event dispatch vector.

p-himik22:01:21

That would be one way to handle that, yes. For some situations. Not a universal solution though.

shaun-mahood22:01:50

For simple things, I generally grab the data directly from the cofx / app-db. I'm not sure if that's a particularly bad practice or not, though.

p-himik22:01:12

It's fine if you're fine with duplicating the logic. Sometimes it's acceptable or even desirable, sometimes it's not.

p-himik22:01:26

re-frame certainly doesn't care about that.

harishtella22:01:42

This is kind of what I had in mind.

(defn search-form
  []
  (let [needed-val (rf/subscribe [:my-sub])]
    (fn []
      [:div#search-form
       [:button {:on-click #(rf/dispatch [:my-event @needed-val])
The downside I see is that this component gets updated whenever the :my-sub subscription changes, when it doesn’t really need to. @shaun-mahood I think that makes sense too. I find it the practice of writing accessor functions for the db somewhat bothersome. Just another set of functions to manage.

p-himik22:01:14

No, don't do that.

p-himik22:01:20

You have to deref the sub first.

harishtella22:01:32

Oh right, of course.

p-himik22:01:13

Just remove the extra (fn [] ...) and move that @ right in front of (rf/subscribe ...) and you're all set.

harishtella22:01:28

(defn search-form
  []
  (let [needed-val @(rf/subscribe [:my-sub])]
    [:div#search-form
      [:button {:on-click #(rf/dispatch [:my-event needed-val])}]]))
Like that, huh? I see, the subscription gets cached, so you don’t need a Form-2 reagent component. Hmm, but I don’t see why I can’t deref the subscription within the #(rf/dispatch ….) anonymous function.

shaun-mahood22:01:34

Since you're referencing that, if you have a chance to read the docs I wrote for that issues and comment on anything that needs more work that would be helpful

p-himik23:01:35

Done. Feel free to @ me in PRs/issues BTW if you think my input would be useful.