Session State How to Show previous choices of filters?

Check the following example. My explanations are in the code.

import streamlit as st
from streamlit import session_state as ss


st.set_page_config(layout='centered')


OPTIONS = ['', 'philippines', 'japan', 'china']  # index=[0, 1, 2, 3]


# A variable used to store the selected value.
if 'selected' not in ss:
    ss.selected = ''


def change():
    """Runs when there is a change in the selectbox."""
    # Sets the current value of widget to the selected variable.
    # The current value of widget is ss.sk where ss is the session state
    # and sk is the key of the widget.
    ss.selected = ss.sk


# The value displayed by the widget is controlled by the index parameter.
# Initially, the index is 0, but this will change depending on the selected value.
st.selectbox(
    'select country',
    index=OPTIONS.index(ss.selected),  # controls what is displayed on widget
    options=OPTIONS,
    key='sk',
    on_change=change
)

References

2 Likes