Problem with session state / components in sidebar in multipage app

Hi, I would like to share components, like a selectbox, across the different pages, in particular in the sidebar. In order to keep the selection across the pages I need to set a default index, the one corresponding to the last item selected.

The selection works fine the first time and is kept when switching from another page. In the same page, however, if the selection is changed more than once, it goes back to the previous value. One needs to repeat it twice for the change to work.

Here is a minimal example: GitHub - blenzi/st_multipage_test: Test of multipage app with streamlit and selectbox in sidebar . When changing the selector from A → B, it works fine. Now within in the same page, trying to do A → B → C, it goes back to B.

Any ideas ?

Thanks

Here is a solution: instead of setting the output to st.session_state one can use the key argument. Example:


choices = ['A', 'B', 'C']
if 'my_choice' not in st.session_state:
    st.session_state = choices[0]
    index = 0
else:
    index = choices.index(st_session_state['my_choice'])

st.selectbox('My choice', choices, index=index, key='my_choice')

Hi @blz,

Sorry I didn’t see your answers here nor this thread there where my response didn’t grasp your problem.

Happy that you found a fix, by the way for future reference here is the problem that happened on your app (see how the widget doesn’t update the first time once it’s on a page)

CleanShot 2022-07-12 at 12.41.58