Session State Variables are re-initialized to initial state going through pages

@ismet_aksoy here is your solution. You need 2 separate variables and a callback function.

import streamlit as st

# Instantiate the Session State Variables
vars = ['name', 'age', 'gender']
for _ in vars:
    if _ not in st.session_state:
        st.session_state[_] = ''

# Sidebar Widgets
st.sidebar.markdown('# Streamlit')
sidebar_pages = st.sidebar.radio('Menu', ['Page 1', 'Page 2', 'Page 3'])

def callback_function(state, key):
    # 1. Access the widget's setting via st.session_state[key]
    # 2. Set the session state you intended to set in the widget
    st.session_state[state] = st.session_state[key]

# Page 1
def page1():
    name = st.text_input('What is your name?', key='name_key', on_change=callback_function, args=('name','name_key'))

# Page 2
def page2():
    age = st.text_input('What is your age?', key='age_key', on_change=callback_function, args=('age','age_key'))

# Page 3
def page3():
    gender = st.text_input('What is your gender?', key='gender_key', on_change=callback_function, args=('gender','gender_key'))

# Navigate through pages
if sidebar_pages == 'Page 1':
    page1()
elif sidebar_pages == 'Page 2':
    page2()
else:
    page3()

st.write(st.session_state)

The key and the session state you want to set cannot be the same. Otherwise, when the new page comes up, the widget is re-drawn, and the widgets key resets the session state.

Here, I added a callback function, which can be used generally for setting most session states from the widgets using on_change and args parameters. Note: if you are going to set a default value on certain widgets, you may need to complicate things with a third varable.

1 Like