Is there anyway for me to force delete / reinitialize the keys tied to button/text input/check box in the session_state?
The reason behind is I have too many keys tied to buttons/text input/check box and the on_click method is not working for me.
I want to make all the keys tied to buttons/text input/check box reinitialized so the buttons/text input/check box displays the default value instead of the key value after experimental_rerun.
Hereโs is an example that I believe should illustrate what you desire:
import streamlit as st
MY_WIDGET_KEYS = {
'key1':'default value 1',
'key2':'default value 2',
'key3':'default value 3'
}
def initialize_all():
for key, value in MY_WIDGET_KEYS.items():
st.session_state[key] = value
def make_it_meow():
for key in MY_WIDGET_KEYS.keys():
st.session_state[key] = 'Meow!'
def clear_all():
for key in MY_WIDGET_KEYS.keys():
st.session_state[key] = ''
if 'key1' not in st.session_state:
initialize_all()
st.text_input('Text 1', key='key1')
st.text_input('Text 2', key='key2')
st.text_input('Text 3', key='key3')
st.write(f'Widget 1: {st.session_state.key1}')
st.write(f'Widget 2: {st.session_state.key2}')
st.write(f'Widget 3: {st.session_state.key3}')
cols=st.columns(3)
cols[0].button('Meow', on_click=make_it_meow)
cols[1].button('Clear', on_click=clear_all)
cols[2].button('Reset', on_click=initialize_all)
You can define a function to assign default values to all your widget keys. (Make sure to not simultaneously use the default value optional parameter in your widgets; just use the values assigned to the keys in session state directly to control the default to avoid a warning that can occur if the default value and key donโt agree.)
Put the initializing function inside a check to see if things are initialized so itโs forced to run on first load. Thereafter you can manually trigger it to re-initialize everything (or overwrite it with other values) when desired.