Button doesn't always work

Summary

Hello everyone, i’m creating an application where users can import a list of names and the app will find similar names to link with, the user can select the name that they find the most similar. It will go trough the imported data 1 by 1 and there’s a selectbox with the suggested matches. Once a match is made this will append to a new dataframe.

However, my app is not doing what i want it to do, when i click “next” on the button it shows the last added row of the new dataframe. When i select an option, it goes to the next row. I don’t know how this happens, maybe it has something to do with caching?

Steps to reproduce

Code snippet:

if 'row' not in st.session_state:
    st.session_state.row = 0

if 'data_new' not in st.session_state:
    st.session_state.data_new = []


data_li = []


col1, col2 = st.columns([5, 5])
with col1:
    st.dataframe(df)

with col2:
    if st.session_state.row < len(df):
        pid = df["id"][st.session_state.row]
        pname = df["name"][st.session_state.row]
        pweight = df["weight"][st.session_state.row]
        tmatch = df["text_matches"][st.session_state.row]
        data_li.append([pid, pname, pweight])
    else:
        st.error("reached end of the file")


    st.dataframe(data_li)

    selection = st.selectbox('Select most similar product: ', options=tmatch + ['Product not found...'])
    approved = st.button("Next")

    if approved:
        st.session_state.row += 1
        st.session_state.data_new.append([pid, pname, pweight, selection])
        print(st.session_state.row)


st.dataframe(st.session_state.data_new)

Debug info

  • Streamlit version: 1.10.0
  • Python version: 3.6.4

What you have now:

  1. You are on some row, say 0, and click next
  2. The page reloads with the row still 0 and that is the row for which data is pulled and displayed
  3. You get to the conditional with approved having a True value
  4. The row is incremented to 1
  5. The data for row 0 is appended

So as written, you need to refresh the page at the end of adding the data so you can reflect that you incremented the row.

if approved:
    st.session_state.row += 1
    st.session_state.data_new.append([pid, pname, pweight, selection])
    print(st.session_state.row)
    # Without the rerun here, your page is not reloading immediately after incrementing the row,
    # so you won't see the new row until something else is interacted with        
    st.experimental_rerun()

Alternatively, you can put the appending of data into a callback function for the Next button, so that you can append data, increment row, then refresh the page so you go straight to displaying the new row.

1 Like

Thank you so much! This helped!

1 Like

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