Need help with updating text in Streamlit app

Hi everyone,

I’m currently having an issue with a piece of code that I’m working on in Streamlit. I’m trying to update the value of a text area based on some user input using a button, but I’m finding that I have to click the button twice in order for the text area to update.

Here’s the code that I’m using:

if "text" not in st.session_state:
    st.session_state["text"] = ""
text1 = st.text_area('Text : ', st.session_state["text"])
before = st.text_input('Before')
after = st.text_input('After')
button = st.button('Button')

if button:
    st.session_state["text"] = text1.replace(before, after)

Does anyone have any suggestions for how I might be able to fix this issue? I’m not sure what’s causing it, and I haven’t been able to find any solutions online so far.

Thanks in advance for any help you can provide!

You are almost there. But when you click the button the script reruns immediately. So the same old text is displayed in the text_area, then st.button('Button') returns True and the text changes, but it is too late because it has already been displayed.

One way to solve this is using a callback instead of an if. Callbacks are called after the button is clicked and before the script reruns.

def replace_text():
    st.session_state["text"] = text1.replace(before, after)

if "text" not in st.session_state:
    st.session_state["text"] = ""
text1 = st.text_area('Text : ', st.session_state["text"])
before = st.text_input('Before')
after = st.text_input('After')
button = st.button('Button', on_click=replace_text)

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