Display content based on session_state variables

Hi, i am trying to display different pages for my app depending on inputs in my session_state.
Page 1: gather group name
Page 2: Once group name has been entered, display a text field for input. After pressing submit, display the text to user.

Here’s a simplified code:

import streamlit as st

if "group" not in st.session_state:
    st.text_input("Group Name:", key="group")
elif st.session_state.group:
    st.header(st.session_state.group)
    feedback = st.text_input("enter feedback")
    submitted = st.button("submit")

    if submitted:
        st.write(feedback)

When user input group name in page 1, the app correctly moves to page 2. However when user key in their feedback in page 2 and press enter/submit, the feedback is not displayed. Instead, it returns to page 1 and the group name disappears. How do i get the feedback to display and the group name to persist even after pressing the submit button?

Thank you.

Hey @erjieyong Thank you for the post!

Having widgets with keys like the text input make the value disappear after the widget disappears, which is causing the issue.

To fix the issue, you make session state have an alternate. This might make the code a little more complex, but it will provide your desired results.

import streamlit as st

if "group" not in st.session_state:
    st.session_state.group = ""
    

def handle_change():
    st.session_state.group = st.session_state.group2

if not st.session_state.group:
    st.text_input("Group Name:", key="group2", on_change=handle_change)
else:
    st.header(st.session_state.group)
    feedback = st.text_input("enter feedback")
    submitted = st.button("submit")

    if submitted:
        st.write(feedback)

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