Update session_state variables fails after submit

Hi there,
I am struggling to understand how session_state works with respect to the submit form. I have a variable that is updated when the a button is pressed. However, when later in the code I submit a form to use that value, it somehow gets back to its original value. The code is:

with st.container():
    st.header("Manual configuration")
    st.write(st.session_state)
    with st.expander("Columns geometry:"):
    col_1,col_2,col_3,col_4,col_5,col_6,col_7,col_8=st.columns(8); # divide the space into columns
    col_2_value=col_2.selectbox("C1 type",options=["S","D","W"],index=1,key="col_2_key");

with st.container():
    def update():
        st.session_state["col_2_key"] = "S";

    column_presets=st.columns(4); # Create the columnspan
    SW_noLoad_button=column_presets[0].button('SW_noLoad',on_click=update);
    st.write(st.session_state["col_2_key"])

The code works and if it returns โ€œSโ€ when the the button is clicked.

However, later on I have a โ€œsubmitโ€ button as:

    with st.form("Run analysis"):
        submitted = st.form_submit_button("Run analysis"); # create button analysis
        if submitted:

When I press the โ€œsubmitโ€ button, the value โ€œSโ€ charges back into โ€œDโ€ again. Thatโ€™s not really clear to me.
Apologies it might be very obvious but could someone please:

  1. explain to me why it happens? It seems like the code re-run again from 0 instead of memorising the value
  2. Help me carry the new value forward into the analysis section?

Thanks a lot for helping.

Hi @Gabriele_Granello , you could try the following with your code:

  1. remove ; from various parts of the code - it is not required
  2. For the statement with the โ€™ selectboxโ€™, delete the key parameter and change the variable name (col_2_value) to st.session_state.col_2_key, like below

st.session_state.col_2_key = col_2.selectbox(โ€œC1 typeโ€, options=[โ€œSโ€,โ€œDโ€,โ€œWโ€], index=1)

Cheers

Thanks a lot for helping @Shawn_Pereira. I think the bug is within the expander, and I have managed to isolate it here:

You can see the screencast too

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