Repository navigation
Description
Describe the bug
The method for setting default var values in a ComponentState-derived class, as described in https://reflex.dev/docs/state-structure/component-state/#passing-props, suggests accessing the var name from cls.__fields__ and overriding the .default attribute.
Unfortunately for inherited fields, all of the subclasses seem to share the exact same Field descriptor, so updating the default in one get_component will affect all other copies of the subclass.
When pydantic was used for this, each subclass got its own fields and thus modifying the default just worked as expected.
To Reproduce
import copy
import reflex as rx
class MyComponent(rx.ComponentState):
text: str = "Default"
items: list[str] = ["Default 1", "Default 2", "Default 3"]
@classmethod
def get_component(cls, *children, **props):
if "initial_value" in props:
cls.__fields__["text"].default = props.pop("initial_value")
if "initial_list" in props:
cls.__fields__["items"].default = props.pop("initial_list")
return rx.text(*children, cls.text, rx.foreach(cls.items, rx.text.span), **props)
@classmethod
def _get_component_working(cls, *children, **props):
if "initial_value" in props:
text_field = copy.deepcopy(cls.get_fields()["text"])
text_field.default = props.pop("initial_value")
cls.__fields__["text"] = text_field
if "initial_list" in props:
items_field = copy.deepcopy(cls.get_fields()["items"])
items_field.default = props.pop("initial_list")
cls.__fields__["items"] = items_field
return rx.text(*children, cls.text, rx.foreach(cls.items, rx.text.span), **props)
def index() -> rx.Component:
return rx.vstack(
MyComponent.create(),
MyComponent.create(initial_value="Hello, World!", initial_list=["Foo", "bar", "baz", "quuc", "grr"], font_size="2em"),
MyComponent.create(initial_value="Goodbye, World!", font_size="1em"),
)
app = rx.App()
app.add_page(index)In this case, renaming _get_component_working to get_component shows a potential workaround where in the Field objects are copied, then the copy is modified and assigned back to the class.
Expected behavior
I expected that all inherited Field objects would be copied into subclasses so that the subclass cannot affect its parents and siblings.
Screenshots
They all have the same values, whatever was set last.
With _get_component_working (expected):
Specifics (please complete the following information):
- Python Version: 3.14.0
- Reflex Version: 0.8.15
- OS: macOS
Activity
docs(design): add PerComponentState design doc