Preserving state across sidebar pages

Hey zabzug! You are pretty much asking for a feature we’re in the middle of heavy design discussions about right this moment!

It’s called SessionState (actual name TBD). Basically, it lets you create a state object that persists per user session, i.e. per open browser tab.

We haven’t hashed out all the details for how the feature would work yet, but here’s a prototype implementation that should do the job for you: https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92

And you can use it this way:

import streamlit as st
import SessionState

st.sidebar.title("Pages")
radio = st.sidebar.radio(label="", options=["Set A", "Set B", "Add them"])

session_state = SessionState.get(a=0, b=0)  # Pick some initial values.

if radio == "Set A":
    session_state.a = float(st.text_input(label="What is a?", value=session_state.a))
    st.write(f"You set a to {session_state.a}")
elif radio == "Set B":
    session_state.b = float(st.text_input(label="What is b?", value=session_state.b))
    st.write(f"You set b to {session_state.b}")
elif radio == "Add them":
    st.write(f"a={session_state.a} and b={session_state.b}")
    button = st.button("Add a and b")
    if button:
        st.write(f"a+b={session_state.a+session_state.b}")

I created a Gist that has both of these code snippets inlined, so you can try it out like this:

streamlit run https://gist.githubusercontent.com/tvst/faf057abbedaccaa70b48216a1866cdd/raw/9938e3863a062842ec14dfd0f0545f349e85a023/session_state_example.py
9 Likes