Session state issue with st.checkbox

I have a small annoying problem with updating session_state from within the app. I first initialise the session state variable in the code, then create st.checkbox with default value bound to the variable. This is all working fine. Now, however, when I try to flip the value, it will take two times to tick the checkbox in order to succeed. Code example below:

if 'test' not in st.session_state:
    st.session_state['test'] = True

if st.checkbox('Flip the value', value=st.session_state['test']):
    st.session_state['test'] = True
else:
    st.session_state['test'] = False```

Hi @tarmojuristo, welcome to the community!! :partying_face: :wave:

Here’s a solution that uses callbacks to avoid the issue of having to interact with the widget twice:

Code

import streamlit as st

# callback to update 'test' based on 'check'
def flip():
    if st.session_state["check"]:
        st.session_state["test"] = True
    else:
        st.session_state["test"] = False

if "test" not in st.session_state:
    st.session_state["test"] = True

st.checkbox(
    "Flip the switch", value=st.session_state["test"], key="check", on_change=flip
)

st.write(st.session_state["test"])

Output

checkbox-state

Happy Streamlit-ing! :balloon:
Snehan

2 Likes

I actually figured out even easier way to solve this problem when I realised that key=‘test’ sets the session state variable for ‘test’ all by itself :slight_smile: So in my original example all that is needed is this:

st.checkbox('Flip the value', key='test')
st.write(st.session_state.test)

But thanks anyway!

Glad you worked out a solution! I assumed you wanted to bind the default value of the checkbox to a session state variable.

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