Last active
April 18, 2021 17:02
-
-
Save ribelo/9d1fdfa05732d3e0a5c4549e23c8d5f2 to your computer and use it in GitHub Desktop.
doxa + re-frame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(require '[ribelo.doxa :as dx]) | |
(require '[re-frame.core :as rf]) | |
;; despite general good practice, in my case it doesn't work to keep all data in | |
;; one db. in every application I have to save some data and removing from store | |
;; data concerning ui and other stuff is not cool. | |
;; declare mutiple db | |
(def default-db (dx/create-dx)) | |
(def market (dx/create-dx)) | |
;; register db | |
(dx/reg-dx! :app re-frame.db/app-db) | |
(dx/reg-dx! :market (r/atom market)) | |
;; with-dx is a macro that assigns a db named keword to ?symbol | |
;; this allows you to conveniently use multiple db's simultaneously without | |
;; requiring them | |
(comment (dx/with-dx [?symbol keyword?] ...)) | |
(rf/reg-fx | |
:commit | |
(fn [data] | |
(if (even? (count data)) | |
(let [it (iter data)] | |
(loop [] | |
(when (.hasNext it) | |
(let [store (.next it) | |
txs (.next it) | |
tx (nth txs 0)] | |
(dx/with-dx [db store] | |
(cond | |
(vector? tx) (dx/commit! db txs) | |
(keyword? tx) (dx/commit! db [txs]))) | |
(recur)))))))) | |
;; from now on you can use `commit` in re-frame effects | |
(rf/reg-event-fx | |
:foo | |
(fn [_ [_ bar baz]] | |
;; {:fx [[:commit [:store-name [transaction or transactions]]]]} | |
{:fx [[:commit [:app [:dx/put [:db/id :foo] :bar bar]]] | |
[:commit [:market [[:dx/put [:db/id :foo] :bar bar] | |
[:dx/put [:db/id :foo] :baz baz]]]]]})) | |
;; if you want to retrieve data from default-db, you can use a simple | |
;; reg-sub | |
(rf/reg-sub | |
:bar | |
(fn [db [_ foo]] | |
(dx/pull db [:bar] [:db/id foo]))) | |
;; or you can use `reg-sub-raw` with `dx/with-dx` | |
(rf/reg-sub-raw | |
:bar-raw | |
(fn [_ [_ foo]] | |
(reagent.ratom/reaction | |
(dx/with-dx [dx_ :app] | |
(dx/pull @dx_ [:bar] [:db/id foo]))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment