pythonstreamlitmulti-page-application

Streamlit real multipage app - Can session.state from select box state synced on all pages?


I'm building a small streamlit app which should show various topics' results through pages. So, on page 1 we have basketball, on page 2 volleyball, etc. Selectbox (dropdown) should be present on each page, allowing the user to switch countries. Is there a way for when the user selects the country on i.e. basketball page to save/apply/sync selection on volleyball page (when user switch page to have selected country automatically applied)?

I'm not using select box as method between pages, but have main page and modules. Sport pages are in the separate folder pages.

Host_Country = st.selectbox('Select HomeTeamName name:',('France', 'Spain', 'Italy', 'England', 'Belgium', 'Portugal','Sweden'), key='country')

Solution

  • The selectbox has an index parameter to represent the value that will be shown in the box. We can use it to update the box. We will use session state to update the index in all pages. The country value is already tracked by st.session_state.country.

    main.py

    import streamlit as st
    
    if 'index' not in st.session_state:
        st.session_state.index = 0
    
    if 'countries' not in st.session_state:
        st.session_state.countries = ('France', 'Spain', 'Italy',
                                      'England', 'Belgium', 'Portugal','Sweden')
    
    st.header('Main')
    
    st.write('Countries')
    st.dataframe(st.session_state.countries)
    

    baskeball.py

    pages/baskeball.py

    import streamlit as st
    
    
    st.header('Basketball')
    
    Host_Country = st.selectbox(
        label='Select HomeTeamName name:',
        options=st.session_state.countries,
        index=st.session_state.index,
        key='country')
    
    # Update the index. It is used in the selectbox.
    st.session_state.index = st.session_state.countries.index(st.session_state.country)
    st.write(f'value of country: {st.session_state.country}')
    

    volleyball.py

    pages/volleyball.py

    import streamlit as st
    
    
    st.header('Volleyball')
    
    Host_Country = st.selectbox(
        label='Select HomeTeamName name:',
        options=st.session_state.countries,
        index=st.session_state.index,
        key='country')
    
    # Update the index. It is used in the selectbox.
    st.session_state.index = st.session_state.countries.index(st.session_state.country)
    st.write(f'value of country: {st.session_state.country}')
    

    Sample

    Select spain in basketball.

    enter image description here

    Go to volleyball page.

    enter image description here

    The country is the same!