Skip to content

Instantly share code, notes, and snippets.

@oliyh

oliyh/header.clj

Created Nov 23, 2018
Embed
What would you like to do?
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