Streamlit Form processes the previously entered Input instead of the Currently submitted one

Hello, I’ve been unable to figure out this issue for a while. I have created a Streamlit form as the frontend for a model. But for some reason, I need to type every input twice before it generates a relevant response.
For example, I boot up my Streamlit app, and type in “List out ABC”. It provides the correct answer.
Next, I delete the input and type “List out DEF”. But it again takes “List out ABC” as the input and provides a related answer!
If I give a different input in my third try, it works again. But then in the 4th try, it repeats the 3rd input, and so on.

Here is the code -

with st.form("query_tabular_data"):
    if 'query_tabular' not in st.session_state:
        st.session_state['query_tabular'] = ''  
          
    query_input = st.text_input("Query:", value=st.session_state['query_tabular'])
    submitted = st.form_submit_button('Submit')
    if submitted:
        st.session_state['query_tabular'] = query_input
        st.write("Current input stored:", st.session_state['query_tabular'])
        colored_header(label='Answer', description='', color_name='green-50')
        with st.spinner("Generating response..."):
                try :    
                    response = test_query(function, st.session_state['query_tabular'])
                except Exception as e:
                    result = 'Error Generating Answer ,'+ str(e)
        #visualization code below

I’ve tried debugging however I can but I’m not particularly experienced with Streamlit so if anyone can point out my mistake it will be much appreciated!

That line is the issue. Try not setting the value. Streamlit will remember it for you. Also, from the remainder of the code, I do not see why you have to use st.session_state at all. You could just use the query_input variable directly.

1 Like

Thank you so much. That did the trick. And noted on the session state as well.