5

I am trying to use session state in streamlit to have a two nested button in which first button click shows recommended movies and second submit button submits a review by user on which a model of sentiment analysis is working. But nested buttons require session state so i tried session state but always getting an error. Below is the code.

if 'rec_btn' not in st.session_state:
        st.session_state.rec_btn= False
    
    def callback():
        st.session_state.rec_btn = True
    
    if st.button('RECOMMEND',key = 'rec_btn'):
      col1, col2, col3 = st.columns(3)
     
      with col1:
          st.image(output_images[0])
          st.markdown(output_names[0].upper())
          review = st.text_input(f"How much you liked the movie {output_names[0]}")
          if st.button('submit',on_click=callback):
                review = re.sub('[^a-zA-Z0-9 ]','',review)
                review = tf_idf_vectorizer.transform([review])
                ans = model_sentiment.predict(review)
                if  ans == 0:
                    review = 'Thanks for your positive review'
                else:
                    review = 'Sorry for your negative review'
                st.write(review)

I am always getting error:

StreamlitAPIException: Values for st.button, st.download_button, st.file_uploader, 
and st.form cannot be set using st.session_state.
desertnaut
  • 57,590
  • 26
  • 140
  • 166

1 Answers1

3

The problem was with how i was using session state for button. Which i was able to understand using this code below. In this way nested button can work together.

import streamlit as st
button1 = st.button('Recommend')
if st.session_state.get('button') != True:

    st.session_state['button'] = button1 # Saved the state

if st.session_state['button'] == True:

    st.write("button1 is True")

    if st.button('Check 2'):

        st.write("Do your logic here")
desertnaut
  • 57,590
  • 26
  • 140
  • 166