reflex icon indicating copy to clipboard operation
reflex copied to clipboard

Can't create instance of `ComponentState` inside `foreach`

Open TimChild opened this issue 1 year ago β€’ 2 comments

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. image

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.

TimChild avatar May 07 '24 00:05 TimChild

We should probably throw an error during compilation, because I don't think the current implementation is supposed to work within rx.foreach anyway.

Lendemor avatar May 07 '24 14:05 Lendemor

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.

TimChild avatar May 07 '24 14:05 TimChild