diff --git a/reflex/event.py b/reflex/event.py index 776bceb21ad..ffd4e70f114 100644 --- a/reflex/event.py +++ b/reflex/event.py @@ -14,6 +14,7 @@ Annotated, Any, Generic, + NoReturn, Protocol, TypedDict, TypeVar, @@ -1683,6 +1684,16 @@ def get_fn_signature(fn: Callable) -> inspect.Signature: class EventVar(ObjectVar, python_types=(EventSpec, EventHandler)): """Base class for event vars.""" + def bool(self) -> NoReturn: + """Get the boolean value of the var. + + Raises: + TypeError: EventVar cannot be converted to a boolean. + """ + raise TypeError( + f"Cannot convert {self._js_expr} of type {type(self).__name__} to bool." + ) + @dataclasses.dataclass( eq=False, @@ -1759,6 +1770,16 @@ def no_args(): class EventChainVar(BuilderFunctionVar, python_types=EventChain): """Base class for event chain vars.""" + def bool(self) -> NoReturn: + """Get the boolean value of the var. + + Raises: + TypeError: EventChainVar cannot be converted to a boolean. + """ + raise TypeError( + f"Cannot convert {self._js_expr} of type {type(self).__name__} to bool." + ) + @dataclasses.dataclass( eq=False, diff --git a/tests/units/test_event.py b/tests/units/test_event.py index e2ead8d93b0..50411f05899 100644 --- a/tests/units/test_event.py +++ b/tests/units/test_event.py @@ -485,6 +485,36 @@ def get_handler(self, arg: Var[str]): _ = rx.input(on_change=w.get_handler) +def test_event_var_in_rx_cond(): + """Test that EventVar and EventChainVar cannot be used in rx.cond().""" + from reflex.components.core.cond import cond as rx_cond + + class S(BaseState): + @event + def s(self): + pass + + handler_var = Var.create(S.s) + with pytest.raises(TypeError) as err: + rx_cond(handler_var, rx.text("True"), rx.text("False")) + assert "Cannot convert" in str(err.value) + assert "to bool" in str(err.value) + + def _args_spec() -> tuple: + return () + + chain_var = Var.create( + EventChain( + events=[S.s()], + args_spec=_args_spec, + ) + ) + with pytest.raises(TypeError) as err: + rx_cond(chain_var, rx.text("True"), rx.text("False")) + assert "Cannot convert" in str(err.value) + assert "to bool" in str(err.value) + + def test_decentralized_event_with_args(): """Test the decentralized event."""