Retain user input values in multipage app when changing pages

I have a keep-retrieve pattern I use when I want to save widget data between pages:


Alternatively, you can also assign a key to every widget you want to keep data for, save all those keys into a list all_my_widget_keys_to_keep then add at the top of every page:

if all_my_widget_keys_to_keep[0] not in st.session_state: # Check if your widget keys exist already
    set_default_values() # Some function that initializes all your values for your widgets

for key in all_my_widget_keys_to_keep:
    st.session_state[key] = st.session_state[key]

This hacky little thing interrupts the widget cleanup process which causes widget keys to get deleted when you navigate away from them. You will also see a simpler:

for key in st.session_state:
    st.session_state[key] = st.session_state[key]

This bypasses the initialization problem, but beware of having certain widgets with keys that don’t like manual assignment like buttons and file uploaders…

1 Like