Clarifying understanding of refreshable example #4385
-
QuestionI was looking at the Refreshable UI with reactive state example here: https://nicegui.io/documentation/refreshable#refreshable_ui_with_reactive_state, with code copied below. from nicegui import ui
@ui.refreshable
def counter(name: str):
with ui.card():
count, set_count = ui.state(0)
color, set_color = ui.state('black')
ui.label(f'{name} = {count}').classes(f'text-{color}')
ui.button(f'{name} += 1', on_click=lambda: set_count(count + 1)) # <-- (1)
ui.select(['black', 'red', 'green', 'blue'],
value=color, on_change=lambda e: set_color(e.value))
with ui.row():
counter('A')
counter('B')
ui.run() I just want to see if I understand correctly. At (1), when the button is clicked, set_count is incremented and being a ui.state element, it proceeds to call counter.refresh()? Okay that's fine - but per the description, the refresh method deletes and recreates the elements. In this case, how is the state preserved across refresh calls? Or are ui.state elements exempted from this deletion? (as a side note, this seems to be only example of using this ui.state element) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @BlankAdventure, You're right, nicegui/nicegui/functions/refreshable.py Line 163 in 1e77878 The nicegui/nicegui/functions/refreshable.py Lines 152 to 157 in 1e77878 |
Beta Was this translation helpful? Give feedback.
Hi @BlankAdventure,
You're right,
set_count
will refresh its target container:nicegui/nicegui/functions/refreshable.py
Line 163 in 1e77878
The
ui.state
is "preserved" because it isn't an element or object, but only a function to create or retrieve a value and a set function. By keeping track of the current index of state variables, it notices whether a new variable needs to be created or if it can return an existing one:nicegui/nicegui/functions/refreshable.py
Lines 152 to 157 in 1e77878