| 
 | 1 | +from starlette.requests import Request  | 
 | 2 | + | 
 | 3 | +from shiny import App, Inputs, Outputs, Session, reactive, render, ui  | 
 | 4 | +from shiny.bookmark import BookmarkState  | 
 | 5 | + | 
 | 6 | + | 
 | 7 | +# App UI **must** be a function to ensure that each user restores their own UI values.  | 
 | 8 | +def app_ui(request: Request):  | 
 | 9 | +    return ui.page_fluid(  | 
 | 10 | +        ui.markdown(  | 
 | 11 | +            "Directions: "  | 
 | 12 | +            "\n1. Change the radio buttons below"  | 
 | 13 | +            "\n2. Changing the radio button will cause a server error."  | 
 | 14 | +            "\n3. The app will save the state to the URL before disconnecting."  | 
 | 15 | +            "\n4. Refresh, your browser. The radio button selection should persist."  | 
 | 16 | +        ),  | 
 | 17 | +        ui.hr(),  | 
 | 18 | +        ui.input_radio_buttons(  | 
 | 19 | +            "letter",  | 
 | 20 | +            "Pick a letter",  | 
 | 21 | +            choices=["A", "B", "C"],  | 
 | 22 | +        ),  | 
 | 23 | +        "Selection:",  | 
 | 24 | +        ui.output_code("letter_out"),  | 
 | 25 | +    )  | 
 | 26 | + | 
 | 27 | + | 
 | 28 | +def server(input: Inputs, output: Outputs, session: Session):  | 
 | 29 | + | 
 | 30 | +    @render.code  | 
 | 31 | +    def letter_out():  | 
 | 32 | +        return input.letter()  | 
 | 33 | + | 
 | 34 | +    @reactive.effect  | 
 | 35 | +    @reactive.event(input.letter, ignore_init=True)  | 
 | 36 | +    async def _():  | 
 | 37 | +        # Simulate a server error when the radio button is changed  | 
 | 38 | +        raise RuntimeError("Simulated server error")  | 
 | 39 | + | 
 | 40 | +    # When the session ends, update the query string with the latest bookmark information  | 
 | 41 | +    @session.on_end  | 
 | 42 | +    async def _():  | 
 | 43 | +        await session.bookmark.update_query_string()  | 
 | 44 | + | 
 | 45 | +    # Reset query string when restoring state  | 
 | 46 | +    @session.bookmark.on_restored  | 
 | 47 | +    async def _(state: BookmarkState):  | 
 | 48 | +        await session.bookmark.update_query_string(session.clientdata.url_pathname())  | 
 | 49 | + | 
 | 50 | + | 
 | 51 | +# Make sure to set the bookmark_store to `"url"` (or `"server"`)  | 
 | 52 | +# to store the bookmark information/key in the URL query string.  | 
 | 53 | +app = App(app_ui, server, bookmark_store="url")  | 
0 commit comments