Skip to content

Instantly share code, notes, and snippets.

@oliyh
Created November 23, 2018 09:37
Show Gist options
  • Save oliyh/7a99b986059832951f28e6a26827dbc1 to your computer and use it in GitHub Desktop.
Save oliyh/7a99b986059832951f28e6a26827dbc1 to your computer and use it in GitHub Desktop.
Patterns for standalone data fetching subscriptions in re-frame
(require '[re-frame.core :as re-frame])
(require '[reagent.ratom :as reagent])
(require '[re-graph.core :as re-graph])
(require '[martian.re-frame :as martian])
;; handler for storing things when they arrive
(re-frame/reg-event-db
::on-things
(fn [db [_ things]]
(assoc db ::raw-things things)))
;; a standalone subscription that manages polling of an http endpoint every 30 seconds
(re-frame/reg-sub-raw
::raw-things
(fn [db _]
(let [polling-interval (* 30 1000)
do-fetch #(re-frame/dispatch [::martian/request :raw-things {} ::on-things])
;; request the data from the server every 30 seconds
poller (js/setInterval do-fetch polling-interval)]
;; if the data is not present right now then fetch it immediately
(when-not (contains? @db ::raw-things)
(do-fetch))
;; return a reaction on the fetched data
(reagent/make-reaction
(fn []
(::raw-things @db))
;; when this re-frame subscription is no longer used, stop the poller
;; and clean up the database too
:on-dispose (fn []
(js/clearInterval poller)
(swap! db dissoc ::raw-things))))))
;; a standalone subscription that manages the lifecycle of its upstream data source (re-graph)
(re-frame/reg-sub-raw
::raw-things
(fn [db _]
;; when the required data is not present start a re-graph subscription to populate it
(when-not (contains? @db ::raw-things)
(re-frame/dispatch [::re-graph/subscribe ::raw-things "{ things { id } }" {} [::on-things]]))
;; return a reaction on the subscription response data
(reagent/make-reaction
(fn []
(::raw-things @db))
;; when this re-frame subscription is no longer used, clean up the re-graph subscription
;; and clean up the database too
:on-dispose (fn []
(re-frame/dispatch [::re-graph/unsubscribe ::raw-things])
(swap! db dissoc ::raw-things)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment