Issue when saving/loading in the session_state the state of a checkbox

I am working on an application in which the status of the whole page can be saved/loaded to/from a file. To do so I opted to set the value of each widget according to a variable stored in the session state that, in turn, is updated whenever the user changes the widgetโ€™s state.

In doing so, however, I stumbled across a strange behavior in which the state of the widget requires a double click by the user to be set correctly.

A minimal example of the problem can be reproduced (streamlit 1.12.2) using the following script:

import streamlit as st

if "X" not in st.session_state:
    st.session_state["X"] = False

st.session_state["X"] = st.checkbox("A checkbox", value=st.session_state["X"])

I was wondering if anyone can explain the cause of this behavior and a possible way to prevent it. At the moment I solved the problem by forcing a page rerun on widget change according to:

import streamlit as st

if "X" not in st.session_state:
    st.session_state["X"] = False

buffer = st.checkbox("A checkbox", value=st.session_state["X"])

if buffer != st.session_state["X"]:
    st.session_state["X"] = buffer

Thanks in advance

1 Like

I also encountered this strange behaviour! In my case, I am trying to keep a default value for a checkbox between switching pages in a multipage app.

Is there any way to avoid this behaviour?

Thanks to the developers for the awesome tool :slight_smile:



I am also encountering this issue. Is anyone else experiencing it?

A fix or a workaround would be very much appreciated!


The recommended way to accomplish this is to use the trick of setting a key on the widget, which automatically syncs the value with the session state.

st.checkbox("A checkbox", key="X")

Once you do that, the session state will stay synced to the widget value without any extra code.

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.