Skip to content

session_state not preserved when using st.switch_page #11115

@drew-wks

Description

@drew-wks

Checklist

  • I have searched the existing issues for similar issues.
  • I added a very descriptive title to this issue.
  • I have provided sufficient information below to help reproduce this issue.

Summary

I encountered an issue while trying to pass data via session_state between the pages in my multi-page app using st.switch_page.

my_repository/
├── streamlit_app.py
├── page_1.py
├── page_2.py

session_state.unit is initialized through a checkbox in streamlit_app.py.
session_state.unit is lost upon clicking st.switch_page on page 2.
Interestingly, session_state.unit is preserved when navigating pages via the sidebar or using st.page_link on page 1.

Reproducible Code Example

>>>>> streamlit_app.py <<<<<<<

import streamlit as st


st.sidebar.checkbox("set unit to True", key="unit")

pages = {
    "Your app": [
        st.Page("page_1.py", title="Page 1"),
        st.Page("page_2.py", title="Page 2"),
    ],
}
pg = st.navigation(pages)
pg.run()


>>>>> page_1.py <<<<<<<
import streamlit as st

st.session_state.unit
st.page_link("page_2.py", label="page_2") # this preserves state


>>>>> page_2.py <<<<<<<
import streamlit as st

st.session_state.unit
back = st.button("< Back to Page 1", type="primary")
if back:
    st.switch_page("page_1.py") # this causes state to be lost

Steps To Reproduce

  1. streamlit run streamlit_app.py
  2. Click the checkbox to turn session_state.unit to True
  3. Navigate to page 2. Notice the value is still True
  4. Click the button
  5. Switches to page 1 and results in the following: AttributeError: st.session_state has no attribute "unit". Did you forget to initialize it?

Expected Behavior

session_state.unit should be preserved after clicking st.switch_page

Current Behavior

Switches to page 1 and produces following:

AttributeError: st.session_state has no attribute "unit". Did you forget to initialize it?

Is this a regression?

  • Yes, this used to work in a previous version.

Debug info

  • Streamlit version: 1.44.1
  • Python version: 3.11
  • Operating System: MacOS
  • Browser: Chrome

Additional Information

No response

Metadata

Metadata

Assignees

Labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions