Selectbox behavior for updating a session state value is not intuitive for my use-case

Hello,

My use-case is about having a selectbox with a set of possible option that get populated dynamically via an API call. The default value should empty/None

Upon selecting a value from the dropdown; another API call will fetch some content and have that rendered as a markdown. The markdown gets updated without a full page refresh everytime a new value is selected

My selectbox gets rendered with:

def _render_main(self):
    self.card = st.selectbox('', list(self.pages.keys()), on_change=self.get_notion_page, placeholder="Select a Card")
    st.markdown(st.session_state.markdown, unsafe_allow_html=True)
    # for debugging only
    st.json(st.session_state)

The on_change function is:

    def get_notion_page(self):
        st.session_state.markdown = StringExporter(block_id=self.pages[self.card]["id"]).export()

This is the only way I managed to get this working but with problems:

  1. On the first load of the page I get the error:

st.session_state has no attribute “markdown”. Did you forget to initialize it?

  1. The markdown does not get updated on first selection; I either have to select it again or if I select another element I will always get the value of the previous selection rendered

Experiments

  • If I try to initialise the session_state variable then I will not get the first error message but then on_change does not seem to change the value at all and it will be always the initial value

Appreciate your help!

streamlit==1.35.0
python=3.10.14

Setting up a key for the selectbox

card = st.selectbox('', list(self.pages.keys()), on_change=self.get_notion_page, placeholder="Select a Card", key="model_card")

and then calling the value using st.session_state fixed it!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.