I would expect a double click needed in case 2.
- Say the widget is in sync: it has itâs initial value and is outputting its initial value.
st.session_state.A2 = st.number_input(
label="What is A2?",
min_value=0, max_value=100,
value=st.session_state.A2,
key='num_A2'
)
- You click on the widget, so
st.session_state.num_A2
is updated instantly and page reloads. - After reloading,
st.session_state.A2
is updated, as an output from the widget (namely after the widget is mounted). - On the next click,
st.session_state.num_A2
is again updated and the page reloads. -
Now although we have a value in
st.session_state.num_A2
which should be correct, the widget sees a new initial value inst.session_state.A2
that it didnât see before, hence Streamlit goes âNew Widget!â - Now since the real value we want is stored in a key associated to a widget that Streamlit thinks has been destroyed, what do we get? âStreamlit doesnât connect back to widgets of the same key if it thinks itâs a different widget.â
- This is an ongoing issue with multipage use cases. Slap in some key preservation at the top (see below), and presto! Youâve just convinced Streamlit that the value associated to the key does not need to be discarded in the cleanup process.
âWell that widget is gone. Letâs get rid of that key value. Oh look, a new widget. No, I donât already have this key. Letâs make one.â- âWhat widget? This key isnât associated to a widget. It was just manually written at the top of the page. Oh look! A new widget and I already have a key of the same name. Iâll connect that up right now.â
My so-called âkey preservationâ for the top of the script:
if 'num_A2' in st.session_state:
st.session_state.num_A2 = st.session_state.num_A2