You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Support for custom event triggers in ComponentStates #3711
I would like to be able to define custom event triggers inside a ComponentState that I can use to drive events in other states.
As an example using ReusableCounter, I define an event trigger called "on_over_ten" that I can pass a value through, and then emit this whenever the counter changes and the value is over 10. I then connect the trigger to a simple MyState "over_ten" event to execute something. Pseudocode without much understanding of how the system fundamentally works:
You can achieve roughly what you are aiming for by doing something like the code copied below. The main points being:
add a ClassVar that will hold the other event handlers you'd like to trigger
register the event handlers to the component .Stateafter you call .create() to make the reusable component.
A new class is made every time .create is called, and is stored in the returned components .State attribute
Be careful about initializing the list of EventHandlers on the ComponentState... E.g. If you were to use a mutable object like a list, and only append to it when registering, all instances of the ComponentState will share the same on_increment_listener list.
return (or yield) the EventHander or list of EventHandlers from the ComponentState event handler method.
The example below consists of two counters, where on one of them I have registered another event handler to listen to the increment method being called.
from typing import ClassVar
import reflex as rx
from reflex_test.templates.template import template
class Counter(rx.ComponentState):
# Define vars that change.
count: int = 0
# Be careful about this being a mutable object.
on_increment_listener: ClassVar[list[rx.EventHandler]] = None
# Define event handlers.
def increment(self) -> list[rx.EventHandler]:
self.count += 1
return self.on_increment_listener
def decrement(self):
self.count -= 1
@classmethod
def get_component(cls, **props):
# Access the state vars and event handlers using `cls`.
return rx.hstack(
rx.button("Decrement", on_click=cls.decrement,
id="button-decrement"),
rx.text(cls.count, id="counter-value"),
rx.button("Increment", on_click=cls.increment,
id="button-increment"),
**props,
)
@classmethod
def register_listener(cls, event_handler: rx.EventHandler) -> None:
if cls.on_increment_listener is None:
cls.on_increment_listener = [event_handler]
else:
cls.on_increment_listener.append(event_handler)
class OtherState(rx.State):
value: int = 0
def increment_when_counter_increments(self):
self.value += 2
@template(route="/counter_example", title="Counter example")
def index() -> rx.Component:
counter = Counter.create()
other_component = rx.card(
rx.vstack(rx.text("I only increment"), rx.text(OtherState.value)))
counter.State.register_listener(
OtherState.increment_when_counter_increments)
counter_2 = Counter.create()
return rx.container(
rx.card(
rx.hstack(
rx.text("The counter:"),
counter,
),
rx.hstack(
rx.text(
"Some other component that updates when the counter increments"),
other_component,
)
),
rx.hstack(
rx.text("Another counter that is separate"),
counter_2,
)
)
I would appreciate some guidance on this issue to ensure I'm understanding the task correctly. From my understanding, we need to implement functionality similar to React's useEffect. To approach this, I have developed the following proof of concept:
class Effects:
_tracked_vars = set()
def __init__(self):
"""
Initializes the Reactive StateManager with the following:
- _tracked_vars: A set of state variables being monitored.
- _effect_handlers: A dictionary mapping state variables to effect functions.
- _pending_effects: A set of state variables whose effects are pending execution.
- _batch_in_progress: A boolean flag indicating whether a batch of updates is in progress.
"""
self._effect_handlers = {}
self._pending_effects = set()
self._batch_in_progress = False
def __setattr__(self, name, value) -> None:
"""
Overrides the default __setattr__ to trigger effects when a tracked variable changes.
If a state variable (tracked variable) is updated and its value has changed:
- If a batch is in progress, the change is added to _pending_effects.
- Otherwise, the relevant effects are triggered immediately.
Args:
name (str): The name of the state variable.
value: The new value to set for the state variable.
"""
if name in self._tracked_vars:
old_value = getattr(self, f"{name}", None)
if old_value != value:
super().__setattr__(name, value)
if self._batch_in_progress:
self._pending_effects.add(name)
else:
self._trigger_effects(name)
else:
super().__setattr__(name, value)
def register_effect(self, effect_fn, dependencies):
"""
Registers an effect function that should be triggered whenever one of the dependent
state variables changes.
Args:
effect_fn (callable): The effect function to be triggered.
dependencies (list): List of state variables (as strings) that the effect depends on.
"""
print(type(effect_fn))
for var in dependencies:
if var not in self._effect_handlers:
self._effect_handlers[var] = set()
self._effect_handlers[var].add(effect_fn)
for var in dependencies:
self._tracked_vars.add(var)
def _trigger_effects(self, var):
"""
Executes all effect functions associated with the given state variable.
Args:
var (str): The name of the state variable whose effects are being triggered.
"""
for effect_fn in self._effect_handlers.get(var, []):
effect_fn()
def apply_pending_effects(self):
"""
Applies all pending effects that were queued during a batch update.
This is called after a batch of updates is completed.
"""
while self._pending_effects:
var = self._pending_effects.pop()
self._trigger_effects(var)
def __getattribute__(self, name):
"""
Overrides __getattribute__ to wrap callable methods in a batching mechanism.
If a method is invoked, it checks if a batch is already in progress. If not,
it starts a batch, calls the method, applies any pending effects, and then
ends the batch.
Args:
name (str): The name of the attribute being accessed.
Returns:
The attribute, or a wrapped function if the attribute is callable.
"""
attr = object.__getattribute__(self, name) # Get the original attribute
if callable(attr): # Check if the attribute is callable (a method)
def wrapper(*args, **kwargs):
if not getattr(self, '_batch_in_progress', False):
self._batch_in_progress = True
result = attr(*args, **kwargs) # Call the original function
self.apply_pending_effects()
self._batch_in_progress = False
else:
result = attr(*args, **kwargs) # Call the original function
return result
return wrapper
else:
return attr
The idea here is to check if state updates have occurred and execute the appropriate effect functions.
Here’s an example of how this can be used:
class ReusableCounter(Effects):
def __init__(self):
super().__init__()
self.count = 0
self.register_effect(self.on_over_ten, ['count'])
self.register_effect(self.on_less_than_zero, ['count'])
def increment(self):
self.count += 1
def decrement(self):
self.count -= 1
def on_over_ten(self):
if self.count > 10:
print("Greater than 10 : count = ", self.count)
def on_less_than_zero(self):
if self.count < 0:
print("Value less than Zero, count = ", self.count)
The code works as expected by detecting state changes and executing corresponding effect functions. However, I’m struggling with how to integrate this with Reflex state. I’m not entirely clear on how Reflex state management works, and I'm encountering errors when trying to inherit the Effects class within a Reflex component.
Could you please review this implementation and provide any guidance on how to properly integrate it with Reflex?
@samarth9201 great investigation, thanks for the work. For your class, wouldn't you need it to still subclass from ComponentState?
The part where the event handler is actually run is over here in the process_event function. All it does though is call the event handler and get the delta afterwards. We could do the apply_pending_effects there but we are trying to keep the code modular and it would be better not to touch the main loop.
I wonder if there's a way to wrap the event handler itself such that it calls apply_pending_effects after it's done. Maybe @masenf can give more insight on this, and if we want to bring this into our core (we will still pay out the bounty for the working solution regardless!)
You're right, the class will inherit from ComponentState. My goal was to prototype the solution outside of Reflex first to ensure the concept works. I'll now look into how to integrate it properly while aligning with Reflex’s design principles.
I'll dive deeper into how this can be done and make sure the solution remains modular. Any further insights or guidance would be greatly appreciated! 🙌
Activity
tsaipraveen99 commentedon Aug 6, 2024
Hi, I would like to work on this. Could you please assign this to me?
Alek99 commentedon Aug 7, 2024
Hi, just assigned you to the other issue. Once that one is done I'll assign this to you if still unclaimed.
bhngupta commentedon Aug 7, 2024
Hello @Alek99, I have gone through the reflex codebase and this seems like an interesting feature to hack on. I would like to take this up.
TimChild commentedon Aug 16, 2024
You can achieve roughly what you are aiming for by doing something like the code copied below. The main points being:
.Stateafter you call.create()to make the reusable component..createis called, and is stored in the returned components.StateattributeThe example below consists of two counters, where on one of them I have registered another event handler to listen to the
incrementmethod being called.dyeruva1225545620 commentedon Aug 27, 2024
Hi, Could you assign this task to me, would love to work on it.
picklelo commentedon Aug 27, 2024
@dyeruva1225545620 just assigned you, let us know if you have issues, ComponentState is a bit tricky
samarth9201 commentedon Sep 14, 2024
Hey, can I get assigned to this issue if no one is working on this?
samarth9201 commentedon Sep 17, 2024
Hello,
I would appreciate some guidance on this issue to ensure I'm understanding the task correctly. From my understanding, we need to implement functionality similar to React's useEffect. To approach this, I have developed the following proof of concept:
The idea here is to check if state updates have occurred and execute the appropriate effect functions.
Here’s an example of how this can be used:
The code works as expected by detecting state changes and executing corresponding effect functions. However, I’m struggling with how to integrate this with Reflex state. I’m not entirely clear on how Reflex state management works, and I'm encountering errors when trying to inherit the Effects class within a Reflex component.
Could you please review this implementation and provide any guidance on how to properly integrate it with Reflex?
Thank you!
picklelo commentedon Sep 19, 2024
@samarth9201 great investigation, thanks for the work. For your class, wouldn't you need it to still subclass from
ComponentState?The part where the event handler is actually run is over here in the
process_eventfunction. All it does though is call the event handler and get the delta afterwards. We could do theapply_pending_effectsthere but we are trying to keep the code modular and it would be better not to touch the main loop.I wonder if there's a way to wrap the event handler itself such that it calls
apply_pending_effectsafter it's done. Maybe @masenf can give more insight on this, and if we want to bring this into our core (we will still pay out the bounty for the working solution regardless!)samarth9201 commentedon Sep 19, 2024
Thanks for the feedback, @picklelo!
You're right, the class will inherit from
ComponentState. My goal was to prototype the solution outside of Reflex first to ensure the concept works. I'll now look into how to integrate it properly while aligning with Reflex’s design principles.I'll dive deeper into how this can be done and make sure the solution remains modular. Any further insights or guidance would be greatly appreciated! 🙌
davewat commentedon Sep 26, 2024
@TimChild From your example code (which works great, btw - thank you!):
Is it possible to pass additional values from the ComponentState to the EventHandler? Modified as:
Thanks!
TimChild commentedon Sep 27, 2024
@davewat
I haven't tried this, but I'd try going down this route:
Have your states implement a protocol (this is mostly for static type checking, but might make the example more clear).
then modify the
Counter.incrementmethod like thisThen you would register a whole state class like:
hongwingl commentedon Jun 16, 2025
If it is just one
EventHandler, you can do this by returning therx.EventHandlerwith the extra argument: