Skip to content

Instantly share code, notes, and snippets.

@swannodette
Last active January 9, 2021 16:09
Show Gist options
  • Save swannodette/11308901 to your computer and use it in GitHub Desktop.
Save swannodette/11308901 to your computer and use it in GitHub Desktop.
Om + DataScript
(ns om-data.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[datascript :as d]))
(enable-console-print!)
(def schema {})
(def conn (d/create-conn schema))
;; prevent cursor-ification
(extend-type d/DB
om/IToCursor
(-to-cursor
([this _] this)
([this _ _] this)))
(d/transact! conn
[{:db/id -1
:title "Hello world!"
:count 0}])
(defn get-conn [owner]
(om/get-shared owner :conn))
(defn app-title [db]
(ffirst
(d/q
'[:find ?title
:where
[?e :title ?title]]
db)))
(defn app-count [db]
(ffirst
(d/q
'[:find ?count
:where
[?e :count ?count]]
db)))
(defn increment [e owner count]
(d/transact! (get-conn owner)
[[:db/add 1 :count (inc count)]]))
(defn app-view [db owner]
(reify
om/IRender
(render [_]
(let [count (app-count db)]
(dom/div nil
(dom/h2 nil (app-title db))
(dom/div nil
(dom/span nil count)
(dom/button
#js {:style #js {:marginLeft "5px"}
:onClick #(increment % owner count)}
"+")))))))
(om/root app-view conn
{:shared {:conn conn}
:target (. js/document (getElementById "app"))})
@scttnlsn
Copy link

@afhammad By passing the db to om/root I believe the entire component tree is re-rendered on every change made to the db.

@livtanong
Copy link

@scttnlsn I've tried following this with a more complex project, and it appears @afhammad is correct. You have to pass the db to all child components that you wish to respond to changes in the db.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment