google/mesop

[Question] Refresh a state value periodically?

Closed this issue · 2 comments

Hello,

I am creating a mesop app and it needs to fetch records every 5 seconds. Here is a basic app that I come up with but it only iterates a pre-defined number of requests and stop. Is there something like setInteval in mesop? Or can you please inform me how to refresh a state value regularly?

import asyncio

import mesop as me


@me.page(path="/")
def page():
    state = me.state(State)
    me.text(f"current value - {state.value}")
    me.text(f"input value - {state.input}")
    me.input(label="Basic input", on_blur=on_blur, value="3")
    me.button("async with yield", on_click=click_async_with_yield)


@me.stateclass
class State:
    value: str
    input: int


def on_blur(e: me.InputBlurEvent):
    state = me.state(State)
    try:
        state.input = int(e.value)
    except Exception:
        state.input = 3


async def fetch_dummy_values(val: int):
    # Simulate an asynchronous operation
    await asyncio.sleep(0.2)
    return f"<async_value> - {val}"


async def click_async_with_yield(e: me.ClickEvent):
    state = me.state(State)
    for i in range(state.input or 3):
        me.state(State).value = await fetch_dummy_values(i)
        yield

Currently the best way to do this is by creating a web component that wraps the settimeout behavior.

For an example ,see https://github.com/google/mesop/tree/main/mesop/examples/web_component/async_action

This web component doesn't do what you want, but it illustrates how you could use set timeout in your code to do the polling.

Hi @richard-to

Thanks for the details.