Skip to content

Commit 5e8c48e

Browse files
committed
prettify
1 parent 636a9a1 commit 5e8c48e

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

examples/workshop/state.cljs

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44
[hx.hooks :as hooks :refer [<-state <-effect <-context]]
55
["react" :as react]))
66

7+
;;
8+
;; A simple counter
9+
;;
10+
711
(defnc Simple [_]
812
(let [state (<-state 0)]
913
[:<>
@@ -13,6 +17,11 @@
1317
(dc/defcard simple
1418
(hx/f [Simple]))
1519

20+
21+
;;
22+
;; A timer that increments each second
23+
;;
24+
1625
(defnc Timer
1726
[opts]
1827
(let [seconds (<-state 0)]
@@ -27,26 +36,43 @@
2736
(dc/defcard timer
2837
(hx/f [Timer]))
2938

39+
40+
;;
41+
;; Using React Context + Hooks for global state management
42+
;;
43+
3044
(def app-state (react/createContext))
3145

3246
(defnc App [{:keys [children]}]
33-
(let [state (<-state {:counter 0})]
47+
(let [state (<-state {})]
3448
[(.-Provider app-state) {:value state}
3549
children]))
3650

37-
(defnc Counter [_]
51+
(defnc CounterConsumer [_]
3852
(let [state (<-context app-state)
3953
{:keys [counter]} @state]
4054
[:<>
4155
[:div "Counter: " counter]
4256
[:button {:on-click #(swap! state update :counter inc)} "inc"]]))
4357

44-
(defnc PrintState [_]
58+
(defnc PrintStateConsumer [_]
4559
(let [state (<-context app-state)]
4660
[:pre (prn-str @state)]))
4761

62+
(defnc TimerConsumer [_]
63+
(let [state (<-context app-state)
64+
{:keys [timer]} @state]
65+
(<-effect (fn []
66+
(let [id (js/setInterval #(swap! state update :timer inc) 1000)]
67+
(fn []
68+
(js/clearInterval id))))
69+
[])
70+
[:<>
71+
[:div "Timer: " timer]]))
72+
4873
(dc/defcard context
4974
(hx/f [App
50-
[PrintState]
51-
[Counter]]))
75+
[PrintStateConsumer]
76+
[TimerConsumer]
77+
[CounterConsumer]]))
5278

0 commit comments

Comments
 (0)