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.