Session_state - how to use it to save values while navigating through a multi_page app?

“Hello everyone! I’m new to Streamlit and I need some help! In the code below, how can I ensure that the widget variables remain saved, even when navigating through different pages of the app? When I return to the page with the code, the values reset to zero! Can you help me?”

def process_form():
			# Inicializa os valores no st.session_state se eles ainda não existirem
			if 'n_ha' not in st.session_state:
				st.session_state['n_ha'] = 0
			if 'p_ha' not in st.session_state:
				st.session_state['p_ha'] = 0
			if 'k_ha' not in st.session_state:
				st.session_state['k_ha'] = 0
			if 's_ha' not in st.session_state:
				st.session_state['s_ha'] = 0

			# Define o formulário
			with st.form(key='my_form'):
				# Define os widgets dentro do formulário
				n_ha = st.number_input('Digite a quantidade de Nitrogênio (N) por ha:', min_value=0, format='%d', key='n_ha_input', value=st.session_state['n_ha'])
				p_ha = st.number_input('Digite a quantidade de Fósforo (P) por ha:', min_value=0, format='%d', key='p_ha_input', value=st.session_state['p_ha'])
				k_ha = st.number_input('Digite a quantidade de Potássio (K) por ha:', min_value=0, format='%d', key='k_ha_input', value=st.session_state['k_ha'])
				s_ha = st.number_input('Digite a quantidade de Enxofre (S) por ha:', min_value=0, format='%d', key='s_ha_input', value=st.session_state['s_ha'])

				# Adiciona um botão submit ao formulário
				submit_button = st.form_submit_button(label='Simular menores custos')

			# Se o botão submit for pressionado e o formulário for submetido
			if submit_button:
				# Armazena os valores dos widgets no st.session_state
				st.session_state['n_ha'] = n_ha
				st.session_state['p_ha'] = p_ha
				st.session_state['k_ha'] = k_ha
				st.session_state['s_ha'] = s_ha
		process_form()

		# Defina as variáveis globalmente para uso posterior
		n_ha = st.session_state['n_ha']
		p_ha = st.session_state['p_ha']
		k_ha = st.session_state['k_ha']
		s_ha = st.session_state['s_ha']

Hi @Marco_Antonio_de_Oli . The following repo will help you that how to manage session for multi pages.
Repo link

I’m also trying to figure out how to share the same session data even when I change from page to page. Session data seems to just randomly (but reliably) disappear when I switch to a new page. Without a solution to this Streamlit is basically useless for anything but single pages.

Hi,

Yes session state is preserved across pages in a multipage app. This is given that the session state variable should be initialized first then accessed at a later point either on the same page or on another page.

An error may arise if a session state is accessed before it is initialized. Thus, it’s always nice to check the code for this possible sequential initialization prior to use.

Hope this helps!

It’s not quite as simple as “yes it just works”. Streamlit definitely has a bug, and this is the thread where I posted my solution:

1 Like

There’s quite a number of threads about retaining state across pages. After reading them and the docs (Widget behavior - Streamlit Docs), I ended up running this function at the top of every page:

def retain_session_state(ss):
    state_vars = ss.keys()
    for var in state_vars:
        if var in ss and not var.startswith("FormSubmitter"):
            ss[var] = ss[var]

where ss=st.session_state
to prevent Streamlit from auto-deleting them.
As long as the widgets’ keys are unique across the pages, I don’t think there’s a problem.
Is there any concern to this approach?