Preserve value of widget after error rerun with session state

Let’s say I have a radio button to choose a color:
[‘Red’, ‘Green’, Blue], and my default is element 0 (‘Red’)
if the user chose ‘Green’, then it stays like that over reruns (which is good), but if there is an error,
the app refreshes itself and selects 0 again (‘Red’), but I want to preserve the user selection.
How can I do it with the session state?

Thanks in advanced :slight_smile:

Hey Ori,

Could you maybe share a code snippet of what you mean/working on exactly?
I’m unsure what kind of error you’re expecting the user to run into, or what kind of error you’re running into currently which makes your application forget the selected color.

Do you already save the color choice in a session state variable? :slight_smile:
Cause putting it in session_state is as simple as something like:

import streamlit as st

if "color" not in st.session_state:
    st.session_state.color = "Red"

color ="Select a color", ["Red", "Green", "Blue"])
st.session_state.color = color
st.write("You chose: ", st.session_state.color)

For now, if you refresh a Streamlit page it will always reset everything because you’re basically making a new connection to the application. There’s no browser/cookie based storage yet.
If you would like to persist things for a user it would be best to save the color to a database and retrieve it for the user on login.

1 Like