Search code examples
streamlit

Prevent page refresh in streamlit


In my streamlit app, I use a form for the user to input some filters (date-range etc). On submit, a visualization is shown with a download-button below to download a CSV of the shown data

Something like (pseudo-code)

with st.form(key="input_parameters"):
    choices = st.multiselect(...) 
    .... more inputs here
    submitted = st.form_submit_button("Submit")

if submitted:
   data = get_data(choices,...)
   st.linechart(data)
   st.download_button("Download CSV",data)

my problem is that after the user clicked the download_button, the page reloads and the graphics disappears. How can I solve that? Is there a way to resubmit the form with the same input again?


Solution

  • The problem is that the script is rerun after the user presses the submit button, resetting submitted to False.

    You can circumvent this behaviour by adding a flag to the session state and check if it was previously set. Maybe there are more elegant ways of doing this, but this is one way:

    import streamlit as st
    import pandas as pd
    import numpy as np
    
    dummy_data = pd.DataFrame(np.random.randint(0, 100, size=(100, 2)), columns=['X', 'Y'])
    try:
        # check if the key exists in session state
        _ = st.session_state.keep_graphics
    except AttributeError:
        # otherwise set it to false
        st.session_state.keep_graphics = False
    
    with st.form(key="input_parameters"):
        choices = st.multiselect('Choose me', ['Plot1', 'Plot2'])
        submitted = st.form_submit_button("Submit")
    
    if submitted or st.session_state.keep_graphics:
        st.line_chart(dummy_data)
        st.session_state.keep_graphics = True
        st.download_button("Download CSV", dummy_data.to_csv())