Session_state update - inside and outside function

Hi Community,

I am facing issue in updating the session state value.I have session state variable outside the form and trying to update the session state variable inside the form after click of submit.

if 'toggle' not in st.session_state:
        st.session_state['toggle']=False

if st.session_state.toggle == False: 
        tab21,tab22, tab11,tab12 = st.tabs(["ON CHART","ON DATA","OFF CHART","OFF DATA"])
else: 
        tab11,tab12, tab21,tab22 = st.tabs(["OFF CHART","OFF DATA","ON CHART","ON DATA"])

with st.form("Manual Override"):
       chkBox=st.checkbox(label='Disable Toggle',value=False,key='Toggleradio')
        submitted = st.form_submit_button("Apply Constraints")
        if submitted:
             if chkBox == True:
                    st.session_state.toggle = not st.session_state.toggle   

Basically i am trying to toggle the tabs with session state. Kindly help me understand where do am i going wrong or code snippets with how to achieve the tabs toggle when there is a variable state change inside the form

Regards
Sridhar Rajaram

Hi @sridharr,

This isn’t complex to achieve, but it’s far more complicated than it needs to be! :frowning:

There have been a few forum posts recently by @mathcatsand on patterns for using session state with callbacks. They’re very clear so I won’t go into using them here. Suffice to say, I used similar ideas to create a working example like yours and posted it here.

Here’s a demo:


HTH,
Arvindra

1 Like

@asehmi

Thanks for immediate response.

Hi, Code flow looks like form is at first place and chart is at second place.

What I am looking like chart is at first place and form is at second place. When updating the session inside form, i need the above chart should render again.

Regards
Sridhar

Hi - The code is there for you to modify at will. The answer focused on how to take form values and apply them immediately to widgets external to the form, using callbacks and session state.

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