Not possible to load origin data in st.data_editor

Summary

Hi all. I created a CRUD-App, where I want to establish a “reset” function to load the original data back to the st.data_editor, after some modifications were done. (e.g.
You see below, that I use st.cache_data in a separate function to call data from a mysql-database. For this example I use hard coded data - but it´s the same procedure.

Steps to reproduce

Code snippet:

import streamlit as st
import pandas as pd

# Create a DataFrame

if st.button("Clear to origin"):
    st.cache_data.clear()

@st.cache_data
def dat_query():
    print("cleared")
    dat = pd.DataFrame([
        {"x": 1, "y": 0},
        {"x": 2, "y": 0},
        {"x": 3, "y": 0},
        {"x": 4, "y": 0}])
    return dat

df = dat_query()

df_ed = st.data_editor(df)

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

If I click “Clear to origin”, I would expect that the data_editor will be initialized with the old data and I see the old data in the web app. The function dat_query is called as expected, but the st.data_editor does not show the original data.

Actual behavior:

The original data will never be shown in the st.data_editor

Debug info

  • Streamlit version: 1.24.1
  • Python version: 3.9.17
  • Using Conda? PipEnv? PyEnv? Pex?
  • OS version: Win 10
  • Browser version: FireFox 102.15.1esr

In general, most widgets preserve their state unless you really force them to change – and one way to do that is by changing the key

import streamlit as st
import pandas as pd


if "random_key" not in st.session_state:
    st.session_state["random_key"] = 0

if st.button("Clear to origin"):
    st.cache_data.clear()
    st.session_state["random_key"] += 1


@st.cache_data
def dat_query():
    print("cleared")
    dat = pd.DataFrame(
        [{"x": 1, "y": 0}, {"x": 2, "y": 0}, {"x": 3, "y": 0}, {"x": 4, "y": 0}]
    )
    return dat


df = dat_query()

df_ed = st.data_editor(df, key=st.session_state["random_key"])

This just increments the key in addition to clearing the cache, which forces the data_editor to reset.

2 Likes

made my day :star_struck:

Thank you so much!

1 Like

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