Manage shared state with PageState
mainFor complex applications where state needs to be shared across different modules or views, use the PageState class.
- Define State: Create a class inheriting from
PageState. Useto_ref()for reactive properties and the@on(self.property)decorator to handle changes. - Access State: In any view or module, use
YourStateClass.get()to retrieve the shared instance of the state. - Integration: This allows multiple views (e.g.,
view1(),view2()) to interact with the same reactive data source.
# state.py
from ex4nicegui import PageState, to_ref, on
class CounterState(PageState):
def __init__(self):
self.count = to_ref(0)
@on(self.count)
def on_count_change(self, val):
print(f"count changed to {val}")
# view.py
from ex4nicegui import rxui
from state import CounterState
def view1():
state = CounterState.get()
ui.label(f"count: {state.count.value} in view1")