Last active
January 22, 2020 06:51
-
-
Save danielneal/f5037a3910fcdc9b5762de8bb67ab1ba to your computer and use it in GitHub Desktop.
Basic context / state for hx
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
... | |
(def app-db (atom {:num 1})) | |
(defnc SomeComponent [] | |
(let [num (db/useSubscription [:db/get-in [:num]]) | |
[rn/View [rn/Text (str num)]]) | |
(defnc App [] | |
[:provider {:context db/context | |
:value app-db} | |
[SomeComponent]]) |
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
(ns cardoon.db | |
(:require | |
[hx.react :as hx] | |
[hx.hooks :as hooks] | |
["react" :as react])) | |
(def context (hx/create-context)) | |
(defmulti subscription (fn [db [k & _]] k)) | |
(defmethod subscription :db/get-in | |
[db [_ path]] | |
(get-in db path)) | |
(defmethod subscription :default | |
[db [k & _]] | |
(js/console.log (str "No subscription handler found for " k))) | |
(defmulti handle-event (fn [db [k & _]] k)) | |
(defmethod handle-event :db/assoc-in | |
[db [_ path value]] | |
(assoc-in db path value)) | |
(defmethod handle-event :default | |
[db [k & _]] | |
(js/console.log (str "No event handler found for " k))) | |
(defn useSubscription | |
[sub] | |
(let [db (hooks/useContext context) | |
[result updateResult] (react/useState (subscription @db sub)) | |
k (gensym)] | |
(hooks/useEffect | |
(fn [] | |
(add-watch db k (fn [_ _ _ db] | |
(let [new-result (subscription db sub)] | |
(when (not= new-result result) | |
(updateResult new-result))))) | |
(fn [] | |
(remove-watch db k))) | |
#js [sub]) | |
result)) | |
(defn useDispatch | |
[] | |
(let [db (hooks/useContext context)] | |
(hooks/useCallback (fn [event] | |
(swap! db (fn [db] (handle-event db event))))))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment