Handling Session State with Streamlit_Option_Menu custom component

Hello,

I have been banging my head against a wall trying to figure out how to keep a variable in session_state while using the streamlit_option_menu custom component (GitHub - victoryhb/streamlit-option-menu). Here is some sample code:

import streamlit as st
from streamlit_option_menu import option_menu

with st.sidebar:
    selected = option_menu("Menu", ['Home', 'Text Analysis'], menu_icon="cast", default_index=0)

if selected == 'Home':
    
    choice = st.radio('Choose an option:', ['A', 'B'])

    if choice == 'A':
        text = st.text_area('Enter Text:')
        submit1 = st.button('Submit Text')
        if submit1:    
            if 'text' not in st.session_state:  ## Here I am intializing the variable to ''
                st.session_state.text = ''               
            st.session_state.text = text  ## And here I am trying to assign the text from the text_area to the variable

if selected == 'Text Analysis':
    submit2 = st.button('Test')
    if submit2:
        print(st.session_state.text)

When the script is running, I enter text in the st.text_area and then hit the submit1 button things seem fine as long as I stay on the ‘Home’ menu option. If I go to “Text Analysis” menu option and click the submit2 button I get an error that “st.session_state.text is undefined”.

I assume what is happening is that the st.session_state.text = text assignment is not carrying over from the “Home” tab to the “Text Analysis” tab, and Im not sure why that is. Any ideas or suggestions are greatly appreciated – thanks!!!

HI @Buckeyes2019,

This is because you have nested the initialization of your variable inside the logic of your code. That is, your user has to select home before text_analysis for the script to initialize it in state.

In practice, whenever I am initializing variables in state, I separate these away from the other code and logic in my app. That way I am sure that all the variables I want to use in the session_state of my app are initialized regardless of when and where I use them.

import streamlit as st
from streamlit_option_menu import option_menu

# initialize ALL state variables:
if 'text' not in st.session_state:  
    st.session_state.text = ""               

with st.sidebar:
    selected = option_menu("Menu", ['Home', 'Text Analysis'], menu_icon="cast", default_index=0)

if selected == 'Home':
    
    choice = st.radio('Choose an option:', ['A', 'B'])

    if choice == 'A':
        text = st.text_area('Enter Text:')
        submit1 = st.button('Submit Text')
        if submit1:    
            st.session_state.text = text  

if selected == 'Text Analysis':
    submit2 = st.button('Test')
    if submit2:
        print(st.session_state.text)

Give this a try and let me know!
Happy Streamlit-ing!
Marisa

1 Like

It worked – thank you Marisa!

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