Issue with Modifying Text using st.text_input and st.button

I’m encountering an issue with Streamlit where I’m trying to allow the user to modify text using st.text_input and then display the modified text when a button is clicked. However, the modified text is not persisting as expected in the session state.

Here’s a simplified version of the code:

import streamlit as st

# Initialize session state
if 'text' not in st.session_state:
    st.session_state.text = "original"

if st.button("show"):
    # Allow the user to modify the text
    st.session_state.text = st.text_input("Edit Text", value=st.session_state.text)

# Display the modified text
st.markdown(st.session_state.text)

if st.button("show again"):
    # Display the modified text
    st.markdown(st.session_state.text)

Despite using st.text_input to modify the text, the “show again” button still displays the original text, not the modified one. I’ve tried using st.text_area as well, but the issue persists.

Can anyone help me understand why the modified text is not persisting in the session state as expected? Any guidance or suggestions would be greatly appreciated!

hi @Raphael_Fabre

The issue you are encountering is related to the way Streamlit handles the session state and the rendering of elements. When you use st.text_input or similar widgets inside a button callback, the changes made by the user are not immediately reflected in the session state. This is because Streamlit does not re-run the entire script in response to a button click.

To address this, you can use the text_input widget directly to capture the user input, and then update the session state with that input.

Here’s an updated version of your code that should work as expected:

import streamlit as st

# Initialize session state
if 'text' not in st.session_state:
    st.session_state.text = "original"

# Allow the user to modify the text
modified_text = st.text_input("Edit Text", value=st.session_state.text)

# Update session state when the user modifies the text
if modified_text != st.session_state.text:
    st.session_state.text = modified_text

# Display the modified text
st.markdown(st.session_state.text)

if st.button("show again"):
    # Display the modified text
    st.markdown(st.session_state.text)

Note:
Streamlit’s session state handling is based on variable equality, so it’s essential to check for changes explicitly if you want to update the session state based on user input.