Replies: 3 comments 1 reply
-
I've found that dictionaries are useful for this. Just define it as a global variable, and use bindings where needed. |
Beta Was this translation helpful? Give feedback.
-
Yes, I've had the exact same itch. I've been using this class to combine state (in a dict, as Frank suggests) and refresh logic: from typing import Callable, Optional
from nicegui import ui
class StatefulRefreshable:
"""Refresh (=rebuild) whenever the included state dict changes (set_values)."""
def __init__(self, state: dict, on_state_change: Optional[Callable[[dict], None]] = None):
self.state = state
self.on_state_change = on_state_change
def set_values(self, new_values: dict):
self.state.update(new_values)
self.refresh()
if self.on_state_change:
self.on_state_change(self.state)
def refresh(self):
self.build.refresh()
@ui.refreshable
async def build(self):
"""Call this for the initial build."""
await self.rebuild()
async def rebuild(self):
"""Implement the build in subclass."""
ui.label(f"{self.__class__.__name__}.rebuild not implemented").classes("text-red")
# which can be used like this...:
class RefreshableFox(StatefulRefreshable):
async def rebuild(self):
fox_text = {
'latin': "velox vulpes salit super piger dogon",
"english": "the quick brown fox jumps over lazy dog",
"german": "der schnelle braune Fuchs springt über den faulen Hund",
}
ui.label(fox_text[self.state["language"]])
@ui.page("/")
async def main():
# def state_change_handler(state: dict):
# ui.notify(f"language changed to {state['language']}")
state = {"language": "english"}
fox = RefreshableFox(state) # optionally add on_state_change=state_change_handler
await fox.build()
radio = ui.radio(
['english', 'german', 'latin'],
value=state['language'],
on_change=lambda: fox.set_values({"language": radio.value})
)
ui.run() Also see #1042 for an older example of the same technique, using a This is not exactly the "global state" that you ask for, but I would make global settings (like language) available in the props I pass to this kind of refreshable component -- where each component has it's own local state, of course. Hope this helps. If you like more involved/complex examples, let me know. |
Beta Was this translation helpful? Give feedback.
-
Hey all, |
Beta Was this translation helpful? Give feedback.
-
Hey guys,
I am searching global state management concept similar like vuex for vue in nicegui, but can not find either in docu or discussions.
basically I am searching how to do with global state management, like global language setting, if the language setting changes all ui should refresh based on the new language.
could someone give some hint, how achieve this in nicegui?
Thank you in advance!
Beta Was this translation helpful? Give feedback.
All reactions