I noticed that st.text_input for caching either doesn’t work properly or I am doing something incorrectly. Below I have an example of a function (printer) returning a hard coded string "Message", which is successfully cached and reappears after a refresh. While the 2nd function (printer2) saves the user input in the cache temporarily but it does not show the text input on the st.write after browser refresh like the first function (printer) despite being very similar functions. The goal is that I want the user input to also be saved in the cache and displayed after refresh for my own personal app. Any ideas on why this isn't working? Variable 'p' is a string type as well.
import streamlit as st
import time
@st.cache_data(experimental_allow_widgets=True)
def printer():
st.write("Running")
time.sleep(3)
return 'Message'
st.write(printer()) #after a refresh "Message" shows up successfully and cached
@st.cache_data(experimental_allow_widgets=True)
def printer2():
p = st.text_input(label='com')
time.sleep(3)
return p
st.write(printer2()) #after a refresh, user text does not show up`
Expected behavior:
Both functions should cache the strings and are shown after a browser refresh
Actual behavior:
Only the first function (printer), shows the string after a refresh, while the 2nd function (printer2) does not. Printer2 seems to cache the string initially but after refresh it disappears.
If you're just looking to persist the user input across app refreshes, I would definitely recommend using session state instead.
Some helpful info on session state:
Session State provides the functionality to store variables across reruns. Widget state (i.e. the value of a widget) is also stored in a session.
For simplicity, we have unified this information in one place. i.e. the Session State. This convenience feature makes it super easy to read or write to the widget's state anywhere in the app's code. Session State variables mirror the widget value using the key argument.
In other words, if you declare your st.text_input
widget with a key, you can then retrieve the value of the widget from session state via that key.
p = st.text_input(label="com", key="p_text_input")
# Write the value of the text input widget
st.write(st.session_state.p_text_input)