Streamlit forms with states

Summary

Unable to initialize a form B upon submitting a form A as the outputs of form A are the inputs of form B.

Code snippet:

if "top10" not in st.session_state:
    st.session_state.top10 = []

if "basket" not in st.session_state:
    st.session_state.basket = []

if "submitted"  not in st.session_state:
    st.session_state.submitted = False

with st.form("Demographics Form"):
    # Ask for demographic input from user
    st.markdown("#### Please fill in the following demographic information:")
    ethnicity = st.selectbox("Ethnicity", demographic_data["Ethnicity"].unique())
    strata = st.selectbox("Strata", demographic_data["Strata"].unique())
    lifestage = st.selectbox("Lifestage", demographic_data["Lifestage"].unique())
    location = st.selectbox("Location", demographic_data["Location"].unique())
    hh_size = st.selectbox("Household Members", demographic_data["#HH"].unique())
    income = st.selectbox("Household Income", demographic_data["Income"].unique())
    bmi = st.selectbox("BMI Category", demographic_data["BMI"].unique())
    obesity = st.selectbox("Obesity", ["1", "0"])
    input_data = pd.DataFrame(
        [[ethnicity, strata, lifestage, location, hh_size, income, bmi, obesity]],
        columns=["Ethnicity", "Strata", "Lifestage", "Location", "#HH", "Income", "BMI", "Obesity"],
    )
    merged_data = pd.concat([demographic_data.drop(['Panel_ID'], axis=1), input_data], axis=0)
    clustering_cols = ["Location", "Lifestage", "Strata", "BMI", "#HH", "Income", "Ethnicity"]
    clustering_data = merged_data[clustering_cols]
    input_cluster = kmodes_clustering(clustering_data, clustering_cols, 5).iloc[-1:]
    top_items = recommend_items(input_cluster)
    submitted = st.form_submit_button("Submit")

if submitted:
    st.session_state.submitted = True
    st.markdown("### Here are the top 10 items that people similar to you are buying!")
    if st.session_state.submitted and st.session_state.top10:
        st.write(st.session_state.top10)
        st.write("Select items to add to your cart:")
        st.multiselect("Items", st.session_state.top10)
        st.button("Add to cart", on_click=st.session_state.update(basket=st.session_state.basket))
        st.write("Items added to cart:", st.session_state.basket)

Expected behaviour:

Upon submitting form B, I want to see the items in the basket

Actual behaviour:

When I submit form B, the session resets and the outputs of form B are not shown.

Hey @usmansiddiqui98,

Thanks for sharing your question! Where are you initializing Form B? Iā€™m only seeing the one form in line 12 (with st.form("Demographics Form"):)