Save file_uploader and text_input state or cache when changing select_box option

Information for a widget’s state is discarded whenever a widget is not rendered (either conditionally or from switching pages). For most widgets (including text_input) you can copy the widget state into a different key and copy it back when the widget reappears:

import streamlit as st

# Initialize and set default value
if '_my_key' not in st.session_state:
    st.session_state._my_key='Default value for the widget'
# Copy from placeholder to widget key
st.session_state.my_key = st.session_state._my_key

def keeper(key):
    # Copy from widget key to placeholder
    st.session_state['_'+key] = st.session_state[key]

st.text_input('Label', key='my_key', on_change=keeper, args=['my_key'])

However, file_uploader doesn’t allow you to assign state like other widgets, so there is a difficulty there. Whenever you change any of the creation parameters of a widget, a new widget will be created.

Possible options:

  1. Render all three at all times and use tabs to switch between them. (You would still lose info if leaving the page and returning.)
  2. Copy the information into another key in session state. The example for text_input is given above, but for file_uploader you would just be storing the files and listing out separately that they are in memory, giving the user the option to use the last submitted or to submit a different batch. (If needed you could make this more robust with options to delete from or add to the existing list from the last render.)
1 Like