Skip to content

Commit

Permalink
prettify
Browse files Browse the repository at this point in the history
  • Loading branch information
lilactown committed Feb 26, 2019
1 parent 636a9a1 commit 5e8c48e
Showing 1 changed file with 31 additions and 5 deletions.
36 changes: 31 additions & 5 deletions examples/workshop/state.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
[hx.hooks :as hooks :refer [<-state <-effect <-context]]
["react" :as react]))

;;
;; A simple counter
;;

(defnc Simple [_]
(let [state (<-state 0)]
[:<>
Expand All @@ -13,6 +17,11 @@
(dc/defcard simple
(hx/f [Simple]))


;;
;; A timer that increments each second
;;

(defnc Timer
[opts]
(let [seconds (<-state 0)]
Expand All @@ -27,26 +36,43 @@
(dc/defcard timer
(hx/f [Timer]))


;;
;; Using React Context + Hooks for global state management
;;

(def app-state (react/createContext))

(defnc App [{:keys [children]}]
(let [state (<-state {:counter 0})]
(let [state (<-state {})]
[(.-Provider app-state) {:value state}
children]))

(defnc Counter [_]
(defnc CounterConsumer [_]
(let [state (<-context app-state)
{:keys [counter]} @state]
[:<>
[:div "Counter: " counter]
[:button {:on-click #(swap! state update :counter inc)} "inc"]]))

(defnc PrintState [_]
(defnc PrintStateConsumer [_]
(let [state (<-context app-state)]
[:pre (prn-str @state)]))

(defnc TimerConsumer [_]
(let [state (<-context app-state)
{:keys [timer]} @state]
(<-effect (fn []
(let [id (js/setInterval #(swap! state update :timer inc) 1000)]
(fn []
(js/clearInterval id))))
[])
[:<>
[:div "Timer: " timer]]))

(dc/defcard context
(hx/f [App
[PrintState]
[Counter]]))
[PrintStateConsumer]
[TimerConsumer]
[CounterConsumer]]))

0 comments on commit 5e8c48e

Please sign in to comment.