Todo application
Demonstrates the use of reactive variables in combinations with dataclasses.
With solara we can get a type safe view onto a field in a dataclass, pydantic model, or attr object.
This is using the experimental solara.lab.Ref
class, which is not yet part of the
official API.
import dataclasses
import solara
from solara.lab import Ref
@dataclasses.dataclass(frozen=True)
class TodoItem:
text: str
done: bool
todo_item = solara.reactive(TodoItem("Buy milk", False))
# now text is a reactive variable that is always in sync with todo_item.text
text = Ref(todo_item.fields.text)
# we can now modify the reactive text variable
# and see its value reflect in the todo_item
text.value = "Buy skimmed milk"
assert todo_item.value.text == "Buy skimmed milk"
# Or, the other way around
todo_item.value = TodoItem("Buy whole milk", False)
assert text.value == "Buy whole milk"
Apart from dataclasses, pydantic models etc, we also supports dictionaries and lists.
todo_items = solara.reactive([TodoItem("Buy milk", False), TodoItem("Buy eggs", False)])
todo_item_eggs = Ref(todo_items.fields[1])
todo_item_eggs.value = TodoItem("Buy eggs", True)
assert todo_items.value[1].done == True
# However, if a list becomes shorter, and the valid index is now out of range, the
# reactive variables will act as if it is "not connected", and will not trigger
# updates anymore. Accessing the value will raise an IndexError.
todo_items.value = [TodoItem("Buy milk", False)]
# anyone listening to todo_item_eggs will *not* be notified.
try:
value = todo_item_eggs.value
except IndexError:
print("this is expected")
else:
raise AssertionError("Expected an IndexError")
Todo
Todo list
Remaining: 2Completed: 1