How to tu update immediatly st.session_state when I click a button

Hi,
imagine this code :

import streamlit as st
with st.container(key="body-custom-chart"):
    col1, col2= st.columns(2)
    with col2:
        if 'var' not in st.session_state:
                st.session_state['var']=0
        else:
            st.write( st.session_state['var'])
    with col1:
           IC=st.button("A1")
           if IC:
                 st.session_state['var']=12
           IB=st.button("A2")
           if IB:
                 st.session_state['var']=13

my problem here is, when I click IB btn st.write( st.session_state[‘var’]) displays 12 and when I click IC btn it displays 13 which is the wrong , van any one help please to change st.session_state[‘var’] immediatly .
thanks

Hi @estem,

The key is to remember that:

  1. Streamlit apps can be thought of as scripts that run from top to bottom
  2. When you make a change further down in a script, it doesn’t affect something farther up in the script unless the script reruns after the change is made

So, there are two options for making the button immediately affect what’s in the session state at the top of the script:

  1. Use st.rerun() after you change st.session_state[“var”] so that it reruns the whole script immediately
  2. (Recommended) use an on_click callback on the button to change st.session_state[“var”]

Here’s a comparison of the two methods:

import streamlit as st

if "var" not in st.session_state:
    st.session_state["var"] = 0

st.write("Var before:")
st.write(st.session_state["var"])

col1, col2, col3 = st.columns(3)
with col1:
    st.write("Original buttons")
    IC = st.button("A1")
    if IC:
        st.session_state["var"] = 12
    IB = st.button("A2")
    if IB:
        st.session_state["var"] = 13

with col2:
    st.write("With st.rerun()")
    IC = st.button("A1", key="a1_v1")
    if IC:
        st.session_state["var"] = 14
        st.rerun()
    IB = st.button("A2", key="a2_v1")
    if IB:
        st.session_state["var"] = 15
        st.rerun()


def set_var(value: int):
    st.session_state["var"] = value


with col3:
    st.write("With on_click")
    IC = st.button("A1", key="a1_v2", on_click=set_var, args=(16,))
    IB = st.button("A2", key="a2_v2", on_click=set_var, args=(17,))

st.write("Var after:")
st.write(st.session_state["var"])

You can see that either method makes st.session_state[“var”] the same at the beginning and the end of the script.

1 Like

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