Help with session state - multi-page app

Summary

I’m having some issues with session state that I"m hoping someone can help. I’m trying to build a multi-page app, after clicking enter on the text input, everything disappears and the session state is not persisted.

Steps to reproduce

  1. click sidebar button.
  2. input text
  3. hit enter.
  4. everything disappears

Code snippet:

import streamlit as st

def main():

    if 'button' not in st.session_state:
        st.session_state.button = False
    
    st.sidebar.button('loader', key='button')

    st.write(st.session_state)

    if st.session_state.button == True:
        input = st.text_input('Write some text')
    else:
        st.write(" ")

if __name__ == '__main__':
    main()

import streamlit as st

def main():

if 'button' not in st.session_state:
    st.session_state.button = False

st.sidebar.button('loader', key='button')

st.write(st.session_state)

if st.session_state.button == True:
    input = st.text_input('Write some text')
else:
    st.write(" ")

if name == ‘main’:
main()


If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

I want the text input to persist for the life cycle of the app (page)

Actual behavior:

Everything disappears and I’m back to step 1.

Debug info

  • Streamlit version: latest
  • Python version: 3.8
  • Using Conda? Conda
  • OS version: MacOS
  • Browser version: Chrome

Links

  • Link to your GitHub repo:
  • Link to your deployed app:

Additional information

If needed, add any other context about the problem here.

Your code raises an exception for me, because you cannot set the state of a button. Buttons don’t have a persistent state so assigning a key to the button is useless for your purpose. Use a callback to change the state instead.

import streamlit as st

def main():
    if 'button' not in st.session_state:
        st.session_state.button = False
    st.sidebar.button('loader', on_click=button_clicked)
    st.write(st.session_state)
    if st.session_state.button:
        input = st.text_input('Write some text')

def button_clicked():
    st.session_state.button = True

if __name__ == '__main__':
    main()
1 Like

Thanks! I didn’t look into the callback feature. This is what I was looking for.

Appreciate the help!

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