Session State variable not updating as expected

I am trying to create a Previous and Next buttons that I can use to pre-fill a text_area based on an array that I am reading in from the file system. Towards the beginning of the program, I initialize a session_state variable for indexing the array. In the callbacks for Next and Previous I am attempting to increase or decrease this session_state variable to index the array accordingly.

The session_state variable does not seem to be updating. When I click Next, it seems to move from 0 (it’s initial state) to 1, but on every subsequent clicks, it reinitializes to 0, and increments to 1. This behavior is replicated in the Previous button as well, which when clicked, resets the session_state variable to 0, and decrements it to -1.

How do I have a persistent session_state variable to index properly?

with open ('data/abouts', 'rb') as file:
    example_summaries = pickle.load(file)

st.session_state.summary_index = 0
...
def prev_callback():
	output_box.markdown(f'{st.session_state.summary_index} -> {st.session_state.summary_index - 1}')
	st.session_state.summary_index = max(0, st.session_state.summary_index - 1)
	st.session_state.summary = example_summaries[st.session_state.summary_index]
	output_box.markdown(f'Summary Index: {st.session_state.summary_index}')

def next_callback():
	output_box.markdown(f'{st.session_state.summary_index} -> {st.session_state.summary_index + 1}')
	st.session_state.summary_index = min(len(example_summaries), st.session_state.summary_index + 1)
	st.session_state.summary = example_summaries[st.session_state.summary_index]
	output_box.markdown(f'Summary Index: {st.session_state.summary_index}')

st.button('Previous', type='secondary', on_click=prev_callback)
st.button('Next', type='secondary', on_click=next_callback)

I have also tried global variables instead of a session_state variable with the same results.

Here is a basic counter app demo.

import streamlit as st
from streamlit import session_state as ss


# Create a variable to hold the counter. See to it
# that the key `cnt` is not yet in session state.
# Intialize it with a value of 0.
if 'cnt' not in ss:
    ss.cnt = 0  # okay we are good


def prev_callback():
    ss.cnt -= 1  # decrement properly


def next_callback():
    ss.cnt += 1  # increment properly


left, center, right = st.columns([1, 1, 1], gap='small')

left.button('Previous', type='secondary', on_click=prev_callback)
center.button(f'{ss.cnt}', type='primary')
right.button('Next', type='secondary', on_click=next_callback)

Just review your code.

2 Likes

Thank you so much. The condition to check whether the session_state variable is present (if 'cnt' not in ss: ss.cnt = 0) solved the issue.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.