import streamlit as st
import random
if "var" not in st.session_state:
st.session_state["var"] = 0
col3,col4 = st.columns(2)
def set_var(value: int):
st.session_state["var"] = value
def setVal(value:int):
set_var(value)
# st.rerun()
with col4:
st.write("Var value:")
st.write(st.session_state["var"])
with col3:
IB = st.button("A2", key="a2_v2") #, on_click=setVal, args=( random.randint(0, 10),))
if IB:
toto=random.randint(0, 10)
st.write(toto)
setVal(toto)
when I click the IB btn logically the toto value should be equal to st.session_state[“var”] but I found a delay between them. I want to resolve it by the st.rerun() but it freeze my application…infinity loop. do you have please any idea how to resolve this issue without using st.rerun()
I don’t think you need the st.rerun here. Since the order of operations with a button is 1. run the callback 2. rerun the entire page, if you use the on_click method you have commented out and put the random int in the setVal function, does that work?
So like this:
import streamlit as st
import random
if "var" not in st.session_state:
st.session_state["var"] = 0
col3,col4 = st.columns(2)
def set_var(value: int):
st.session_state["var"] = value
def setVal(value: int):
set_var(random.randint(0, 10))
with col4:
st.write("Var value:")
st.write(st.session_state["var"])
with col3:
IB = st.button("A2", key="a2_v2", on_click=setVal)
thanks for your time and efforts, in fact I dont want to pass setVal like this on_click=setVal, i kew it works…but in my real usecase I need to use functions directly I dont have btns…this is the reason why…I tried st.rerun() but it did infinity loop. do you have any idea please ?
Any chance you can share the real use case/full code? I think I’m confused - an infinite loop would usually be a bug, either in your code or potentially in the streamlit rerun