reflex-dev / reflex

🕸️ Web apps in pure Python 🐍
https://reflex.dev
Apache License 2.0
20.41k stars 1.18k forks source link

Custom components with ComponentState not compatible with rx.foreach #3718

Open MarcoTuc opened 4 months ago

MarcoTuc commented 4 months ago

When a Custom component is created with a custom state, if declared via rx.foreach, then all the created components will share the same state. Below an example that works as I explained on reflex 0.5.7

class ReusableCounter(rx.ComponentState):
    count: int = 0

    def increment(self):
        self.count += 1

    def decrement(self):
        self.count -= 1

    @classmethod
    def get_component(cls, **props):
        return rx.hstack(
            rx.button("Decrement", on_click=cls.decrement),
            rx.text(cls.count),
            rx.button("Increment", on_click=cls.increment),
            **props,
        )

reusable_counter = ReusableCounter.create

def multiple_counters():
    return rx.foreach(
        rx.Var.range(3),
        lambda i: rx.hstack(
            rx.text(f"Counter {i}"),
            reusable_counter(),
        )
    )
benedikt-bartscher commented 3 months ago

Dynamic States are currently not possible in reflex because all state names need to be known at compile time. I would love to see a solution for dynamic states in general and later use it in ComponentState.

I did some exploration in #3671 and #3683

yutayouguan commented 3 months ago

has any progress on the issue , it puzzled for a long time,

paoloemilioserra commented 3 weeks ago

looking for an update on this eventually