Accept input into a list and display the list

So I am trying to accept user input from a text box then add the input to a list, the text box should subsequently accept more inputs and keep adding to the list and displays the list at every new item added
But each time I add a new input, it overwrites the previous one
Here is my code snippet

import streamlit as st

def main():
    
    # Creating a list of reviews (serves as the database in this use case)
    list_of_reviews = []
    
    # Disply structure
    st.title('TEXT SENTIMENT ANALYZER')
    col = st.columns(2)

    # input section
    with col[0].form(key='input form'):
        user_input = st.text_input('Review product')
        
        button = st.form_submit_button(label='Submit')
        
        if button:
            list_of_reviews.append(user_input)

    st.write(f'Review Count: {len(list_of_reviews)}')
    
    #reviews section
    st.subheader('REVIEWS')   
    for i in list_of_reviews:
        st.write('*',i)

how do I fix it

Create a session variable so that it will not be overwritten as streamlit reruns the code from to bottom whenever there are changes to the state of object.

Something like

if 'list_of_reviews' not in st.session_state:
    st.session_state.list_of_reviews = []   
st.session_state.list_of_reviews.append(...)

@ferdy it worked
Thanks

1 Like

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