Updating session_state output when it's before the change

Is there a way in streamlit to update session_state output when it’s before the change?

st.session_state.x = 'x'

st.write(st.session_state.x) # Outputs x instead of y

st.session_state.x = 'y'

I have a real example on my job where I want to update a title when the radio input right after it is changed, but didn’t find yet a way to do it.

Make the change in the on_change callback.

I’ve read the streamlit docs for statefullness apps, but the only examples they gave was by using a button with on_click, but they didn’t add even a single one with on_change, so I didn’t get the right way to use it, could you please show me an example?

I tried using something like: answer = st.radio(on_change=name_funtion, args=(answer)) but it says that it cannot use answer as args cause it wans’t declared yet, so how would I get the input from the user?

I realized you might not even need a callback. Here is a minimal example, I hope it can help you get started. Let me know if it doesn’t work for your use case.

import streamlit as st

if "text" not in st.session_state:
    st.session_state["text"] = "Left"

st.radio("Side", ["Left", "Right"], key="text")
1 Like

Actually I had to write a little more of code to work on my case. I my project I needed to do some conditionals to change the output on the header, not just get the exact input from the radio option.

So I did something like this and it worked:

import streamlit as st

if 'text' not in st.session_state:
    st.session_state.text = 'Left'

if st.session_state.text == 'Left':
  title = 'Left Foo'
  title = 'Right Foo'

st.write(f' ### The | {title}')
st.radio('Side', ['Left', 'Right'], key='text')

Thank you dude! God Bless you!