I’m facing an issue with state persistence in my Streamlit application. Below is a snippet of my code:
<code>if 'Test' not in st.session_state:
st.session_state['Test'] = None
if 'Test1' not in st.session_state:
st.session_state['Test1'] = None
st.session_state['Test'] = col1_page1.selectbox('Test', options=['A', 'B', 'C'], index=0)
st.session_state['Test1'] = col1_page1.selectbox('Test1', options=['A', 'B', 'C'], index=['A', 'B', 'C'].index(st.session_state['Test1']) if st.session_state['Test1'] is not None else 0)
</code>
<code>if 'Test' not in st.session_state:
st.session_state['Test'] = None
if 'Test1' not in st.session_state:
st.session_state['Test1'] = None
st.session_state['Test'] = col1_page1.selectbox('Test', options=['A', 'B', 'C'], index=0)
st.session_state['Test1'] = col1_page1.selectbox('Test1', options=['A', 'B', 'C'], index=['A', 'B', 'C'].index(st.session_state['Test1']) if st.session_state['Test1'] is not None else 0)
</code>
if 'Test' not in st.session_state:
st.session_state['Test'] = None
if 'Test1' not in st.session_state:
st.session_state['Test1'] = None
st.session_state['Test'] = col1_page1.selectbox('Test', options=['A', 'B', 'C'], index=0)
st.session_state['Test1'] = col1_page1.selectbox('Test1', options=['A', 'B', 'C'], index=['A', 'B', 'C'].index(st.session_state['Test1']) if st.session_state['Test1'] is not None else 0)
Problem Description:
- When I enter my Streamlit application and choose an option in the first select box (‘Test’), then navigate to another page via the sidebar and return to the first page, the selected option is reset and not remembered.
- For the second select box (‘Test1’), I have managed to fix this issue, and the selected option saved when navigating between pages. However, when I try to choose a different option, the select box requires two clicks to update, and
st.session_state['Test1']
changes only on the second click.
Questions:
- Why does the first select box (‘Test’) not remember the selected option when navigating between pages?
- Why does the second select box (‘Test1’) require two clicks to update the selected option?
- Do you have any suggestions or better methods to save the selected index across pages without initializing it?
I’ve included a reproducible example in the code snippet above. Any insights or suggestions would be greatly appreciated!
Thank you!
New contributor
Dima GitHub is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.