Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't create instance of ComponentState inside foreach #3238

Open
TimChild opened this issue May 7, 2024 · 2 comments
Open

Can't create instance of ComponentState inside foreach #3238

TimChild opened this issue May 7, 2024 · 2 comments
Labels
bug Something isn't working

Comments

@TimChild
Copy link

TimChild commented May 7, 2024

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.

@Lendemor Lendemor added the bug Something isn't working label May 7, 2024
@Lendemor
Copy link
Collaborator

Lendemor commented May 7, 2024

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

@TimChild
Copy link
Author

TimChild commented May 7, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants