Cache with session state? (Make text Input appear after refresh?)

Hi everyone, I’m making a single page app that will have many plots and users will need to comment below each plot in a textbox. As a result, after the user leaves or refreshes app, the text in the comment still needs to be on the app. I was thinking this involves caching and session states, but I couldn’t get it to work. Check out my basic example below in which that after user types in the text box and refreshes, it doesn’t save and display the text. Anyone have an advice on how to fix this? Thank you

import streamlit as st

@st.cache_data(experimental_allow_widgets=True) 
def comment():
    s = st.text_input(label='Comment',key = 'KEY', on_change=handle,label_visibility='collapsed')
    return s

#------------------------------------------------------------------------------------

#SESSION STATES

if 'empty_comm' not in st.session_state:
      st.session_state['empty_comm'] = ''

def handle(): 
    if st.session_state.KEY:
        st.session_state.empty_comm = st.session_state.KEY
      
#-------------------------------------------------------------------------------------

#APP LAYOUT
    
with st.container():
        comment()

Expected behavior:

Should type in text box, press enter, then refresh page. After refresh, the text should still be in the text box.

Actual behavior:

User inputs text, presses enter, and refreshes but the text box is still blank after the refresh

Debug info

  • Streamlit version: 1.24.0
  • Python version: 3.10
  • Using Conda? Yes. Anaconda Spyder
  • OS version: MacOS Monterey 12.6.7
  • Browser version: Mozilla 118.0.1 (64-bit)

Hi @kapzillion

There’s a related forum post on having data persist after app refresh that suggests using session state or a cookies component.

Additionally you can also save those information to an external database.

Also, you can try saving the text inputs to a file and then after the app refreshes you can reload that file (if it exists).

Hope this helps!

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