re-frame/docs/FAQs/UseASubscriptionInAnEventHa...

56 lines
1.5 KiB
Markdown
Raw Normal View History

2017-01-06 23:33:01 +00:00
### Question
2017-08-01 01:22:15 +00:00
How do I access the value of a subscription from within an event handler?
2017-07-31 12:24:52 +00:00
### The Wrong Way
You should NOT do this:
```clj
(re-frame.core/reg-event-db
:event-id
(fn [db v]
(let [sub-val @(subscribe [:something])] ;; <--- Eeek
2017-08-01 01:22:15 +00:00
....)))
2017-07-31 12:24:52 +00:00
```
2017-08-01 01:22:15 +00:00
because that `subscribe`:
1. might create a memory leak (the subscription might not be "freed")
2. makes the event handler impure (it grabs a global value)
2017-07-31 12:24:52 +00:00
### The Better Way
2017-01-06 23:33:01 +00:00
Instead, the value of a subscription should
2017-07-31 12:24:52 +00:00
be injected into the `coeffects` of that handler via an interceptor.
2017-01-06 23:33:01 +00:00
2017-08-01 01:22:15 +00:00
A sketch:
2017-07-31 12:24:52 +00:00
```clj
(re-frame.core/reg-event-fx ;; handler must access coeffects, so use -fx
2017-07-31 12:24:52 +00:00
:event-id
(inject-sub [:query-id :param]) ;; <-- interceptor will inject subscription value into coeffects
(fn [coeffects event]
(let [sub-val (:something coeffects)] ;; obtain subscription value
2017-07-31 12:24:52 +00:00
....)))
```
2017-01-06 23:33:01 +00:00
2017-08-01 01:22:15 +00:00
Notes:
1. `inject-sub` is an interceptor which will get the subscription value and add it to coeffects (somehow)
2. The event handler obtains the value from coeffects
So, how to write this `inject-sub` interceptor?
2017-08-01 01:22:15 +00:00
2017-07-31 12:24:52 +00:00
### Solutions
2017-08-01 01:22:15 +00:00
re-frame doesn't yet have a builtin `inject-sub` interceptor to do this injection.
2017-07-31 12:24:52 +00:00
2017-08-01 01:22:15 +00:00
I'd suggest you use this 3rd party library:
2017-07-31 12:24:52 +00:00
https://github.com/vimsical/re-frame-utils/blob/master/src/vimsical/re_frame/cofx/inject.cljc
2017-01-06 23:33:01 +00:00
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
2017-01-06 23:33:01 +00:00