Skip to content

Commit

Permalink
fix: reactive ref should be an instance of Reactive to work with use_…
Browse files Browse the repository at this point in the history
…reactive (#544)

This make the todo app fail, since it would wrap the ref in a reactive
var.
  • Loading branch information
maartenbreddels committed Mar 8, 2024
1 parent 0bc6a2d commit 7592d49
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
10 changes: 8 additions & 2 deletions solara/toestand.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,9 +496,12 @@ def wrapper(f: Callable[[], T]):
return wrapper(f)


class ReactiveField(ValueBase[T]):
class ReactiveField(Reactive[T]):
def __init__(self, field: "FieldBase"):
super().__init__() # type: ignore
# super().__init__() # type: ignore
# We skip the Reactive constructor, because we do not need it, but we do
# want to be an instanceof for use in use_reactive
ValueBase.__init__(self)
self._field = field
field = field
while not isinstance(field, ValueBase):
Expand Down Expand Up @@ -558,6 +561,9 @@ def peek(self) -> T:
def set(self, value: T):
self._field.set(value)

def update(self, *args, **kwargs):
ValueBase.update(cast(ValueBase, self), *args, **kwargs)


def Ref(field: T) -> Reactive[T]:
_field = cast(FieldBase, field)
Expand Down
20 changes: 19 additions & 1 deletion tests/unit/toestand_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ def ThemeInfo():
@react.component
def ThemeSelector():
theme, set_theme = Ref(settings.fields["theme"]).use_state() # type: ignore
with sol.ToggleButtonsSingle(theme, on_value=set_theme) as main:
with sol.ToggleButtonsSingle(theme, on_value=set_theme) as main: # type: ignore
sol.Button("dark")
sol.Button("light")
return main
Expand Down Expand Up @@ -1016,6 +1016,24 @@ def Test():
rc.close()


def test_use_reactive_ref():
reactive_var = Reactive({"a": 1})
reactive_ref = Ref(reactive_var.fields["a"])

reactive_ref_test: Reactive[int] = None

@solara.component
def Test():
nonlocal reactive_ref_test
reactive_ref_test = solara.use_reactive(reactive_ref)
return solara.IntSlider("test: " + str(reactive_ref.value), value=reactive_ref_test)

box, rc = solara.render(Test(), handle_error=False)
assert reactive_ref_test is not None
assert reactive_ref_test.value == 1
rc.close()


def test_use_reactive_on_change():
control = Reactive(0)
var1 = Reactive(1)
Expand Down

0 comments on commit 7592d49

Please sign in to comment.