Streamlit session state resetting for unknown reason

App is running locally.
Streamlit version 1.38.0

I am trying to create a page where a user can click on buttons ideally, or checkboxes.
Which will then clear what is on the page and display new content.

import streamlit as st

st.session_state

def session_state_creation():
    if 'key_1' not in st.session_state:
        st.session_state['key_1'] = False

    if 'key_2' not in st.session_state:
        st.session_state['key_2'] = False

session_state_creation()

st.session_state

def inital_load_stuff():
    checkbox_1 = st.checkbox('list', key='key_1')

    checkbox_2 = st.checkbox('list', key='key_2')

def initial_load():
    if (st.session_state['key_1'] == False and st.session_state['key_2'] == False):
        inital_load_stuff()

initial_load()

if st.session_state['key_1'] == True:
    st.button('anything')

if st.session_state['key_2'] == True:
    st.button('anything')

st.session_state

So in this example the initial page loads and creates key_1 and key_2 in sessions state with False values. After selecting one of the checkboxes the screen clears and now displays the new button “anything”.

If a user clicks on this button streamlit re-runs as intended, but sessions state gets cleared which then makes the sessions_state_creation function run. This behavior happens with anything that re-runs the page. In my actual code I am trying to display an aggrid table when a button or checkbox is selected. If the user selects anywhere on the table causing a re-run the user is taken back to the inital screen with buttons or checkboxes.

I am unsure if it is a bug or I am missing something, but why is the session state being cleared?

When the checkboxes are not rendered their state is lost. You can avoid that by unconditionally assign a value to the keys.

def session_state_creation():
    st.session_state['key_1'] = st.session_state.get('key_1', False)
    st.session_state['key_2'] = st.session_state.get('key_2', False)

Thanks! @Goyo

Working the way I want it now.

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