@ui.refreshable always syncs all browsers and tabs? #4054
-
QuestionWhen I run this example, every time I press enter on the Input all open tabs pointed at the URL (127.0.0.1:8000) across all browsers on my laptop sync to result of refresh_cp on that tab. Is this expected? e.g. I open a chrome browser tab and load http://127.0.0.1:8000/, then a 2nd tab to that URL, then a tab on Edge for that URL. All are showing just the blank line for the Input. I type "1" then enter in the first tab, and "random1: 1" shows up in all 3 tabs. If I go to another tab and type "2" then enter, "random2: 2" is displayed in all 3 tabs. Then very surprising: back to tab 1, type "11" then enter and all 3 tabs now display "random1: 1 random1: 11"! This proves that the self.texts variable is being maintained separately for each tab. import random
from nicegui import ui
from nicegui.elements.input import Input
class PageInstanceData:
def __init__(self):
self.id = random.randint(0, 999)
self.texts: list[str] = []
class TestPage1:
def __init__(self, path: str):
@ui.refreshable
async def refresh_cp(idata: PageInstanceData) -> None:
for text in idata.texts:
ui.label(f'{idata.id}: {text}')
async def handle_enter(prompt_input: Input, idata: PageInstanceData) -> None:
idata.texts.append(f'{prompt_input.value.strip()}')
refresh_cp.refresh(idata)
@ui.page(path)
async def index() -> None:
idata = PageInstanceData()
prompt_input = ui.input().on('keydown.enter', lambda: handle_enter(prompt_input, idata))
await refresh_cp(idata)
if __name__ in {'__main__', '__mp_main__'}:
cp = TestPage1('/')
ui.run(host='localhost', port=8000, show=False, reload=False) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @8forty, You're declaring the refreshable function once for all clients. This is why it shows the same content in all three tabs. |
Beta Was this translation helpful? Give feedback.
Hi @8forty,
You're declaring the refreshable function once for all clients. This is why it shows the same content in all three tabs.
This is explained in https://nicegui.io/documentation/refreshable#global_scope. The following sections demonstrate how to use refreshables with local scope.