import streamlit as st
st.session_state.headlines_list = ['a', 'b', 'c']
if "selected_headline" not in st.session_state:
st.session_state.selected_headline = 0
selected_headline = st.sidebar.selectbox(
"Select a Headline",
options=st.session_state.headlines_list,
index=st.session_state.selected_headline
)
st.session_state.selected_headline = st.session_state.headlines_list.index(selected_headline)
import streamlit as st
for k, v in st.session_state.items():
st.session_state[k] = v
HEADLINES = ["a", "b", "c"]
Any other page
import streamlit as st
from main import HEADLINES
for key, val in st.session_state.items():
st.session_state[key] = val
selected_headline = st.sidebar.selectbox(
"Select a Headline",
options=HEADLINES,
key="selected_headline",
)
import streamlit as st
HEADLINES = ["a", "b", "c"]
pages/first.py
import streamlit as st
from main import HEADLINES
for k, v in st.session_state.items():
st.session_state[k] = v
selected_headline = st.sidebar.selectbox(
"Select a Headline",
options=HEADLINES,
key="selected_headline",
)
pages/second.py
import streamlit as st
from main import HEADLINES
for k, v in st.session_state.items():
st.session_state[k] = v
selected_headline = st.sidebar.selectbox(
"Select a Headline",
options=HEADLINES,
key="selected_headline",
)
And it works fine, but I’m not certain if this is a good practice.
Should I have the same key for the component in the 2 pages considering it’s meant to be the same component?
for k, v in st.session_state.items():
st.session_state[k] = v
This makes sure that the session state is preserved across pages. We’re working on a more natural way to ensure that, but it’s the best option currently.
Using the same key on different pages is not a problem, and if you combine it with that session state trick above, it should keep the widgets in-sync with each other and with session state