Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: table data not refreshing after mo.output.replace() when first-page data is unchanged (#8066)

Myles Scolnickcaf9a99f51e8
diff --git a/frontend/src/components/data-table/__tests__/data-table.test.tsx b/frontend/src/components/data-table/__tests__/data-table.test.tsx
index fbfe131aee..6fc2885eae 100644
--- a/frontend/src/components/data-table/__tests__/data-table.test.tsx
+++ b/frontend/src/components/data-table/__tests__/data-table.test.tsx
@@ -1,6 +1,11 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import type { ColumnDef, RowSelectionState } from "@tanstack/react-table";
-import { render, screen } from "@testing-library/react";
+import type {
+ ColumnDef,
+ PaginationState,
+ RowSelectionState,
+ SortingState,
+} from "@tanstack/react-table";
+import { render, screen, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
import { DataTable } from "../data-table";
@@ -95,4 +100,91 @@ describe("DataTable", () => {
expect(rows[1]).toHaveAttribute("title", "Michael Scott");
expect(rows[2]).toHaveAttribute("title", "Jim Halpert");
});
+
+ it("should display updated data after rerender with manual sorting and pagination", () => {
+ // Simulates the bug from issue #8023:
+ // When a user sorts a table, rows that moved from page 2 to page 1
+ // don't visually refresh after the underlying data is updated.
+
+ interface RowData {
+ id: number;
+ status: string;
+ value: number;
+ }
+
+ // Initial data: 4 rows, page_size=3
+ const initialData: RowData[] = [
+ { id: 4, status: "pending", value: 40 },
+ { id: 3, status: "pending", value: 30 },
+ { id: 2, status: "pending", value: 20 },
+ ];
+
+ const columns: ColumnDef<RowData>[] = [
+ { id: "id", accessorFn: (row) => row.id, header: "id" },
+ { id: "status", accessorFn: (row) => row.status, header: "status" },
+ { id: "value", accessorFn: (row) => row.value, header: "value" },
+ ];
+
+ // Simulate sorted state (value descending) - manual sorting means
+ // data comes pre-sorted from backend
+ const sorting: SortingState = [{ id: "value", desc: true }];
+ const setSorting = vi.fn();
+
+ const paginationState: PaginationState = { pageIndex: 0, pageSize: 3 };
+ const setPaginationState = vi.fn();
+
+ const commonProps = {
+ columns,
+ selection: null as "single" | "multi" | null,
+ totalRows: 4,
+ totalColumns: 3,
+ pagination: true,
+ manualPagination: true,
+ paginationState,
+ setPaginationState,
+ manualSorting: true,
+ sorting,
+ setSorting,
+ };
+
+ const { rerender } = render(
+ <TooltipProvider>
+ <DataTable {...commonProps} data={initialData} />
+ </TooltipProvider>,
+ );
+
+ // Verify initial data is displayed - look for "pending" in cells
+ const rows = screen.getAllByRole("row");
+ // Row 0 is header, rows 1-3 are data rows
+ expect(rows).toHaveLength(4); // 1 header + 3 data rows
+ // All rows should show "pending"
+ expect(within(rows[1]).getByText("pending")).toBeTruthy();
+ expect(within(rows[2]).getByText("pending")).toBeTruthy();
+ expect(within(rows[3]).getByText("pending")).toBeTruthy();
+
+ // Now simulate data update: row with id=4 is now "approved"
+ // Backend returns sorted data with the update applied
+ const updatedData: RowData[] = [
+ { id: 4, status: "approved", value: 40 },
+ { id: 3, status: "pending", value: 30 },
+ { id: 2, status: "pending", value: 20 },
+ ];
+
+ // Rerender with updated data (same sorting, same pagination)
+ rerender(
+ <TooltipProvider>
+ <DataTable {...commonProps} data={updatedData} />
+ </TooltipProvider>,
+ );
+
+ // BUG: The row should show "approved" but might show stale "pending"
+ const updatedRows = screen.getAllByRole("row");
+ expect(updatedRows).toHaveLength(4);
+
+ // The first data row (id=4) should now show "approved"
+ expect(within(updatedRows[1]).getByText("approved")).toBeTruthy();
+ // Other rows should still show "pending"
+ expect(within(updatedRows[2]).getByText("pending")).toBeTruthy();
+ expect(within(updatedRows[3]).getByText("pending")).toBeTruthy();
+ });
});
diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsx
index ad51e96a7c..751e1588f0 100644
--- a/frontend/src/core/MarimoApp.tsx
+++ b/frontend/src/core/MarimoApp.tsx
@@ -39,14 +39,18 @@ const LazyGalleryPage = reactLazyWithPreload(
);
export function preloadPage(mode: string) {
- if (mode === "home") {
- LazyHomePage.preload();
- } else if (mode === "gallery") {
- LazyGalleryPage.preload();
- } else if (mode === "read") {
- LazyRunPage.preload();
- } else {
- LazyEditPage.preload();
+ switch (mode) {
+ case "home":
+ LazyHomePage.preload();
+ break;
+ case "gallery":
+ LazyGalleryPage.preload();
+ break;
+ case "read":
+ LazyRunPage.preload();
+ break;
+ default:
+ LazyEditPage.preload();
}
}
diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
index beb7f3509a..da266ceb12 100644
--- a/frontend/src/plugins/core/registerReactComponent.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -101,10 +101,17 @@ function PluginSlotInternal<T>(
return plugin.validator.safeParse(parseDataset(hostElement));
});
+ // Incremented on each reset to invalidate memoized function references.
+ // This ensures that plugin functions (e.g., search) are re-created when
+ // the underlying UI element instance changes (new object-id), even if
+ // the element's data attributes haven't changed.
+ const [resetNonce, setResetNonce] = useState(0);
+
useImperativeHandle(ref, () => ({
reset: () => {
setValue(getInitialValue());
setParsedResult(plugin.validator.safeParse(parseDataset(hostElement)));
+ setResetNonce((n) => n + 1);
},
setChildren: (children) => {
setChildNodes(children);
@@ -224,7 +231,8 @@ function PluginSlotInternal<T>(
}
return methods;
- }, [plugin.functions, hostElement]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [plugin.functions, hostElement, resetNonce]);
// If we failed to parse the initial value, render an error
if (!parsedResult.success) {
diff --git a/frontend/src/plugins/impl/__tests__/DataTablePlugin.test.tsx b/frontend/src/plugins/impl/__tests__/DataTablePlugin.test.tsx
new file mode 100644
index 0000000000..1895b61a70
--- /dev/null
+++ b/frontend/src/plugins/impl/__tests__/DataTablePlugin.test.tsx
@@ -0,0 +1,164 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { TooltipProvider } from "@radix-ui/react-tooltip";
+import { act, render, screen, waitFor } from "@testing-library/react";
+import { Provider } from "jotai";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import type { DownloadAsArgs } from "@/components/data-table/schemas";
+import type { FieldTypesWithExternalType } from "@/components/data-table/types";
+import { store } from "@/core/state/jotai";
+import {
+ type GetDataUrl,
+ type GetRowIds,
+ LoadingDataTableComponent,
+} from "../DataTablePlugin";
+
+beforeAll(() => {
+ global.ResizeObserver = class ResizeObserver {
+ observe() {
+ // do nothing
+ }
+ unobserve() {
+ // do nothing
+ }
+ disconnect() {
+ // do nothing
+ }
+ };
+});
+
+describe("LoadingDataTableComponent", () => {
+ /**
+ * Regression test for https://github.com/marimo-team/marimo/issues/8023
+ *
+ * When a table is replaced via mo.output.replace() with updated data,
+ * but the initial page data (unsorted first page) hasn't changed,
+ * the useAsyncData hook's deps may all remain the same.
+ * Previously, the `search` function reference was memoized on
+ * [plugin.functions, hostElement] and wouldn't change on reset(),
+ * so the useAsyncData effect wouldn't re-fire.
+ *
+ * The fix adds a resetNonce to the functionMethods memo deps,
+ * so when the plugin is reset (table instance changes), the search
+ * function reference changes, triggering useAsyncData to re-fetch.
+ *
+ * This test verifies that when the search function reference changes
+ * (simulating reset()), the component re-fetches data even if
+ * props.data hasn't changed.
+ */
+ it("should refetch data when search function reference changes", async () => {
+ const host = document.createElement("div");
+ const setValue = vi.fn();
+
+ // The initial page data string - identical for both renders.
+ // This simulates the case where only a row on page 2 changed,
+ // so the first page data is the same.
+ const initialPageData = JSON.stringify([
+ { id: 1, status: "pending", value: 10 },
+ { id: 2, status: "pending", value: 20 },
+ { id: 3, status: "pending", value: 30 },
+ ]);
+
+ const searchResult = {
+ data: [
+ { id: 1, status: "pending", value: 10 },
+ { id: 2, status: "pending", value: 20 },
+ { id: 3, status: "pending", value: 30 },
+ ],
+ total_rows: 4,
+ cell_styles: null,
+ cell_hover_texts: null,
+ };
+
+ const searchFn1 = vi.fn().mockResolvedValue(searchResult);
+ const searchFn2 = vi.fn().mockResolvedValue(searchResult);
+
+ const fieldTypes: FieldTypesWithExternalType = [
+ ["id", ["integer", "integer"]],
+ ["status", ["string", "string"]],
+ ["value", ["integer", "integer"]],
+ ];
+
+ const commonProps = {
+ label: null,
+ totalRows: 4,
+ pagination: true,
+ pageSize: 3,
+ selection: "single" as const,
+ showDownload: false,
+ showFilters: false,
+ showColumnSummaries: false as const,
+ showDataTypes: false,
+ showPageSizeSelector: false,
+ showColumnExplorer: false,
+ showRowExplorer: false,
+ showChartBuilder: false,
+ rowHeaders: [] as FieldTypesWithExternalType,
+ fieldTypes,
+ totalColumns: 3,
+ maxColumns: "all" as const,
+ hasStableRowId: false,
+ lazy: false,
+ host,
+ enableSearch: true,
+ value: [] as (number | string | { rowId: string; columnName?: string })[],
+ setValue,
+ download_as: vi.fn() as DownloadAsArgs,
+ get_column_summaries: vi.fn().mockResolvedValue({
+ data: null,
+ stats: {},
+ bin_values: {},
+ value_counts: {},
+ show_charts: false,
+ }),
+ get_data_url: vi.fn() as GetDataUrl,
+ get_row_ids: vi.fn() as GetRowIds,
+ };
+
+ const Wrapper = ({ children }: { children: React.ReactNode }) => (
+ <Provider store={store}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </Provider>
+ );
+
+ // Render with first search function
+ const { rerender } = render(
+ <Wrapper>
+ <LoadingDataTableComponent
+ {...commonProps}
+ data={initialPageData}
+ search={searchFn1}
+ />
+ </Wrapper>,
+ );
+
+ // Wait for the table to render with data
+ await waitFor(() => {
+ expect(screen.getAllByRole("row").length).toBeGreaterThan(1);
+ });
+
+ // Search was called on initial load (fire-and-forget for canShowInitialPage)
+ expect(searchFn1).toHaveBeenCalled();
+
+ // Now rerender with the same data but a NEW search function reference.
+ // This simulates what happens after reset() when resetNonce increments
+ // and functionMethods is recreated.
+ await act(async () => {
+ rerender(
+ <Wrapper>
+ <LoadingDataTableComponent
+ {...commonProps}
+ data={initialPageData}
+ search={searchFn2}
+ />
+ </Wrapper>,
+ );
+ });
+
+ // The new search function should be called because the search
+ // dependency changed in useAsyncData.
+ await waitFor(() => {
+ expect(searchFn2).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/frontend/src/utils/__tests__/mime-types.test.ts b/frontend/src/utils/__tests__/mime-types.test.ts
index 60ea5a9f1c..1a180f0c2e 100644
--- a/frontend/src/utils/__tests__/mime-types.test.ts
+++ b/frontend/src/utils/__tests__/mime-types.test.ts
@@ -132,7 +132,7 @@ describe("mime-types", () => {
describe("sortByPrecedence", () => {
it("should sort entries by precedence order", () => {
- const entries: Array<[MimeType, string]> = [
+ const entries: [MimeType, string][] = [
["text/plain", "plain"],
["text/html", "html"],
["image/png", "png"],
@@ -151,7 +151,7 @@ describe("mime-types", () => {
});
it("should place unknown mime types at the end", () => {
- const entries: Array<[MimeType, string]> = [
+ const entries: [MimeType, string][] = [
["text/plain", "plain"],
["text/html", "html"],
["application/json", "json"],
@@ -173,7 +173,7 @@ describe("mime-types", () => {
});
it("should handle empty precedence", () => {
- const entries: Array<[MimeType, string]> = [
+ const entries: [MimeType, string][] = [
["text/plain", "plain"],
["text/html", "html"],
];
@@ -184,7 +184,7 @@ describe("mime-types", () => {
});
it("should not mutate original array", () => {
- const entries: Array<[MimeType, string]> = [
+ const entries: [MimeType, string][] = [
["text/plain", "plain"],
["text/html", "html"],
];
@@ -198,7 +198,7 @@ describe("mime-types", () => {
describe("processMimeBundle", () => {
it("should filter and sort mime entries", () => {
- const entries: Array<[MimeType, string]> = [
+ const entries: [MimeType, string][] = [
["text/plain", "plain"],
["text/html", "html"],
["image/png", "png"],
@@ -226,7 +226,7 @@ describe("mime-types", () => {
});
it("should use default config when not provided", () => {
- const entries: Array<[MimeType, string]> = [
+ const entries: [MimeType, string][] = [
["text/html", "html"],
["image/png", "png"],
["text/markdown", "md"],
@@ -240,9 +240,7 @@ describe("mime-types", () => {
it("should preserve data associated with mime types", () => {
const htmlData = { content: "<h1>Hello</h1>" };
- const entries: Array<[MimeType, typeof htmlData]> = [
- ["text/html", htmlData],
- ];
+ const entries: [MimeType, typeof htmlData][] = [["text/html", htmlData]];
const result = processMimeBundle(entries);
@@ -250,7 +248,7 @@ describe("mime-types", () => {
});
it("should sort by precedence after filtering", () => {
- const entries: Array<[MimeType, string]> = [
+ const entries: [MimeType, string][] = [
["text/plain", "plain"],
["text/markdown", "md"],
["text/html", "html"],
diff --git a/frontend/src/utils/mime-types.ts b/frontend/src/utils/mime-types.ts
index 603f4a368e..63f5064d8b 100644
--- a/frontend/src/utils/mime-types.ts
+++ b/frontend/src/utils/mime-types.ts
@@ -26,7 +26,7 @@ export interface MimeTypeConfig {
*/
export interface ProcessedMimeTypes<T> {
/** The filtered and sorted mime entries */
- entries: Array<[MimeType, T]>;
+ entries: [MimeType, T][];
/** Mime types that were hidden by rules */
hidden: MimeType[];
}
@@ -146,9 +146,9 @@ export function applyHidingRules(
* Mime types not in the map are placed at the end, preserving their original order.
*/
export function sortByPrecedence<T>(
- entries: Array<[MimeType, T]>,
+ entries: [MimeType, T][],
precedence: ReadonlyMap<MimeType, number>,
-): Array<[MimeType, T]> {
+): [MimeType, T][] {
const unknownPrecedence = precedence.size;
return [...entries].sort((a, b) => {
@@ -162,7 +162,7 @@ export function sortByPrecedence<T>(
* Main entry point: processes mime entries by applying hiding rules and sorting.
*/
export function processMimeBundle<T>(
- entries: Array<[MimeType, T]>,
+ entries: [MimeType, T][],
config: MimeTypeConfig = getDefaultMimeConfig(),
): ProcessedMimeTypes<T> {
if (entries.length === 0) {
@@ -176,6 +176,6 @@ export function processMimeBundle<T>(
return {
entries: sortedEntries,
- hidden: Array.from(hidden),
+ hidden: [...hidden],
};
}
diff --git a/marimo/_smoke_tests/issues/8023_stale_table.py b/marimo/_smoke_tests/issues/8023_stale_table.py
new file mode 100644
index 0000000000..f475a723ff
--- /dev/null
+++ b/marimo/_smoke_tests/issues/8023_stale_table.py
@@ -0,0 +1,54 @@
+import marimo
+app = marimo.App()
+
+def _():
+ import marimo as mo
+ import pandas as pd
+ return mo, pd
+
+def _(mo):
+ data_version, set_data_version = mo.state(0)
+ return data_version, set_data_version
+
+def _():
+ data = [
+ {"id": 1, "status": "pending", "value": 10},
+ {"id": 2, "status": "pending", "value": 20},
+ {"id": 3, "status": "pending", "value": 30},
+ {"id": 4, "status": "pending", "value": 40},
+ ]
+ return (data,)
+
+def _(data, data_version, mo, pd):
+ _ = data_version()
+ df = pd.DataFrame(data)
+ table = mo.ui.table(df, selection="single", page_size=3)
+ mo.output.replace(table)
+ return (table,)
+
+def _(mo):
+ approve_btn = mo.ui.run_button(label="Approve")
+ mo.output.replace(approve_btn)
+ return (approve_btn,)
+
+def _(approve_btn, data, set_data_version, table):
+ import time
+ if approve_btn.value:
+ _sel = table.value
+ if _sel is not None and len(_sel) > 0:
+ _id = _sel.iloc[0]["id"]
+ for item in data:
+ if item["id"] == _id:
+ item["status"] = "approved"
+ break
+ set_data_version(time.time())
+ return
+
+if __name__ == "__main__":
+ app.run()