Update st.date_editor content

Summary

Dear Streamlit-Community,
I want to use the st.data_editor to look up values from a database based on values that I enter into the column “Search value”. Whenever the “Search”-Button is pressed, I want to update the >> existing << st.data_editor with values from fake_result_table (For the sake of simplification let’s assume whenever the button is pressed, a script queries an imaginary data source and returns the fake dataframe).

Steps to reproduce

Code snippet:

import streamlit as st
import pandas as pd


with st.form("my_form"):
    if "template" not in st.session_state:
        st.session_state["template"] = pd.DataFrame(columns=["Search Value", "Result"])

    input = st.data_editor(st.session_state["template"], num_rows="dynamic")

    search = st.form_submit_button("Search")
    if search:
        fake_result_table = pd.DataFrame(
            [[1, "A"], [2, "B"], [3, "C"]], columns=["Search Value", "Result"]
        )
        st.session_state["template"] = fake_result_table

Expected behavior:

The input widget (st.data_editor) is updated / content is replaced by the pd.DataFrame called fake_result_table. Important: I only want 1 st.data_editor > I want to display the results in the same widget in wich I inserted the search values.

Actual behavior:
The st.data_editor is only updating the very first time. When I change the results afterwards and press “Search” again, everything remains the same. No matter what I tryed (working with session state/ st.empty() etc., I couldn’t get the desired result.

1 Like

The only way I know of to force the data_editor to be recreated is to change the key – so, this is a silly solution, but it seems to do what you want:

import streamlit as st
import random
import pandas as pd


if "template" not in st.session_state:
    st.session_state["template"] = pd.DataFrame(columns=["Search Value", "Result"])

if "key" not in st.session_state:
    st.session_state["key"] = random.randint(0, 100000)


def search_callback():
    fake_result_table = pd.DataFrame(
        [[1, "A"], [2, "B"], [3, "C"]], columns=["Search Value", "Result"]
    )
    st.session_state["template"] = fake_result_table
    st.session_state["key"] = random.randint(0, 100000)


input = st.data_editor(
    st.session_state["template"],
    num_rows="dynamic",
    key=str(st.session_state["key"]),
)

search = st.button("Search", on_click=search_callback)
2 Likes

Great! This worked for me. Thank you!

2 Likes

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