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 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')
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)
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.