Prepopulate Input Using Session State

I have an application that has multiple β€˜pages’ similar to the code below. I’d like to be able to prepopulate input widgets with values set by the user previously. The code I have written below does that, but there is weird behavior when trying to modify the text value. You have to enter the input twice in order to set a new value. The first input just gets erased.

import streamlit as st   #1.6.0

def load_previous_input(label):
    """If it exists, populate input with previous user entry, otherwise None"""
    return st.session_state[label] if label in st.session_state else None

def save_input(label, new_value):
    """Overwrite previous input with new input"""
    st.session_state[label] = new_value

with st.sidebar:
    selected_page ='Select Page', ['Page 1', 'Page 2'])

if selected_page == 'Page 1':
    label = 'Enter Some Text'
    value = load_previous_input(label)
    user_text = st.text_input(label, value) if value is not None else st.text_input(label)
    save_input(label, user_text)
elif selected_page == 'Page 2':
    st.write("""Page 2: User does stuff on this page, when clicking back to Page 1, I want the field to
    prepopulate with what they entered before (if it exists). It seemingly works, (prepopulates with previous input)
    but look what happens when you try to change the text...

Is this a bug with Streamlit? Or is there a better way to accomplish this?


I have the exact same issue with drop down boxes, seems to be a streamlit issue. What happen is your default value get updated only after you enter user_text which needs two round of reloads. Anyone have solution?

I raised this issue on their Github, and when they responded the text inputs (and all other inputs other than multiselect, seemed to just start working all of a sudden despite me not changing the code or the Streamlit version? Still very confused on how that was possible. Anyways, this was their solution. Honestly, not entirely satisfied with their answer. I feel like the multiselect behavior is still buggy as it does not act like other inputs using this same method successfully (without use of st.form).

@BurritoQuest There is a new component can help to resolve this issue. I love it, give it a try!!

You definetely have to give your widgets a key value to avoid such issues. I am not 100% sure if this is the same case, however I had a similar question a couple months ago: Make a widget remember its value after it is hidden and shown again in later script runs - #3 by Wally

This is how I am doing it in all of my apps on streamlit 1.11.0 currently.

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