@@ -40,12 +40,16 @@ whose body contains a hook usage. We'll demonstrate that with a simple
40
40
import idom
41
41
42
42
43
- @idom.component
44
- def ClickCount():
43
+ def use_counter():
45
44
count, set_count = idom.hooks.use_state(0)
45
+ return count, lambda: set_count(lambda old_count: old_count + 1)
46
+
46
47
48
+ @idom.component
49
+ def ClickCount():
50
+ count, increment_count = use_counter()
47
51
return idom.html.button(
48
- {"onClick": lambda event: set_count(count + 1 )},
52
+ {"onClick": lambda event: increment_count( )},
49
53
[f"Click count: {count}"],
50
54
)
51
55
@@ -79,15 +83,17 @@ which we can re-render and see what changed:
79
83
80
84
static_handler = StaticEventHandler()
81
85
86
+
82
87
@idom.component
83
88
def ClickCount():
84
- count, set_count = idom.hooks.use_state(0 )
89
+ count, increment_count = use_counter( )
85
90
86
91
# we do this in order to capture the event handler's target ID
87
- handler = static_handler.use(lambda event: set_count(count + 1 ))
92
+ handler = static_handler.use(lambda event: increment_count( ))
88
93
89
94
return idom.html.button({"onClick": handler}, [f"Click count: {count}"])
90
95
96
+
91
97
with idom.Layout(ClickCount()) as layout:
92
98
patch_1 = await layout.render()
93
99
@@ -124,27 +130,28 @@ callback that's called by the dispatcher to collect events it should execute.
124
130
import asyncio
125
131
126
132
from idom.core.layout import LayoutEvent
127
- from idom.core.dispatch import dispatch_single_view
133
+ from idom.core.dispatcher import dispatch_single_view
128
134
129
135
130
136
sent_patches = []
131
137
138
+ # We need this to simulate a scenario in which events ariving *after * each update
139
+ # has been sent to the client. Otherwise the events would all arive at once and we
140
+ # would observe one large update rather than many discrete updates.
141
+ sempahore = asyncio.Semaphore(0)
142
+
132
143
133
144
async def send(patch):
134
145
sent_patches.append(patch)
146
+ sempahore.release()
135
147
if len(sent_patches) == 5:
136
148
# if we didn't cancel the dispatcher would continue forever
137
149
raise asyncio.CancelledError()
138
150
139
151
140
152
async def recv():
153
+ await sempahore.acquire()
141
154
event = LayoutEvent(target=static_handler.target, data=[{}])
142
-
143
- # We need this so we don't flood the render loop with events.
144
- # In practice this is never an issue since events won't arrive
145
- # as quickly as in this example.
146
- await asyncio.sleep(0)
147
-
148
155
return event
149
156
150
157
0 commit comments