Can't create instance of `ComponentState` inside `foreach`
Describe the bug
Attempting to call the create method on a ComponentState inside of a foreach call results in a ReferenceError on the frontend (only if the ComponentState has any reference to cls in the returned component).
To Reproduce Steps to reproduce the behavior:
import reflex as rx
from reflex_test.templates import template
class Comp(rx.ComponentState):
value: int = 0
@classmethod
def get_component(cls, v, *children, **props) -> "Component":
return rx.card(
rx.text(f"I'm a component with state {v}"), # <<< This alone works
rx.text(f"I'm a component with state {cls.value}"), # <<< Adding this causes error
)
@template(route='/component_state_in_foreach_issue', title='Component State in Foreach Issue')
def index() -> rx.Component:
return rx.container(
rx.foreach(
[1, 2, 3],
Comp.create,
),
)
Expected behavior Expect 3 separate components to be created without error.
Screenshots
If applicable, add screenshots to help explain your problem.
Specifics (please complete the following information):
- Python Version: 3.12
- Reflex Version: 4.9
- OS: WSL2
- Browser (Optional): Chrome
I think I will fall back to using a state that stores a list of an rx.Base subclass that holds the state for each item and just include the index in any calls back to event handlers so that I can update the appropriate item.
We should probably throw an error during compilation, because I don't think the current implementation is supposed to work within rx.foreach anyway.
Yea, I think that probably is a good solution, at least in the short term. I'm not sure if the State attribute on the rx.Component is exclusively for the rx.ComponentStatates, but if so, then just checking for components with that set inside the foreach would be enough.