Skip to content

Commit f09c2e2

Browse files
authored
fix(toolbar-search): re-filter rows if DataTable rows change (#2154)
Fixes #2143 Make `ToolbarSearch` filtering reactive to `DataTable` rows. Previously, `ToolbarSearch` did not update when `DataTable` rows changed. Now it subscribes to the context rows and re-runs `filterRows` in `afterUpdate` to prevent infinite loops.
1 parent b034378 commit f09c2e2

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/DataTable/ToolbarSearch.svelte

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,15 +46,39 @@
4646
*/
4747
export let ref = null;
4848
49-
import { tick, getContext } from "svelte";
49+
import { tick, getContext, afterUpdate, onMount } from "svelte";
5050
import Search from "../Search/Search.svelte";
5151
5252
const ctx = getContext("DataTable") ?? {};
5353
54+
let rows = null;
55+
let unsubscribe = null;
56+
5457
$: if (shouldFilterRows) {
55-
filteredRowIds = ctx?.filterRows(value, shouldFilterRows);
58+
unsubscribe = ctx?.tableRows.subscribe((tableRows) => {
59+
// Only update if the rows have actually changed.
60+
// This approach works in both Svelte 4 and Svelte 5.
61+
if (JSON.stringify(tableRows) !== JSON.stringify(rows)) {
62+
rows = tableRows;
63+
}
64+
});
65+
} else {
66+
rows = null;
5667
}
5768
69+
onMount(() => {
70+
return () => {
71+
unsubscribe?.();
72+
};
73+
});
74+
75+
afterUpdate(() => {
76+
// Only filter rows in a callback to avoid an infinite update loop.
77+
if (rows !== null) {
78+
filteredRowIds = ctx?.filterRows(value, shouldFilterRows);
79+
}
80+
});
81+
5882
async function expandSearch() {
5983
await tick();
6084
if (disabled || persistent || expanded) return;

tests/DataTable/DataTableSearch.test.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,7 @@ describe("DataTableSearch", () => {
182182
});
183183
});
184184

185-
// TODO: fix reactivity
186-
it.skip("re-filters rows when toggled", async () => {
185+
it("re-filters rows when toggled", async () => {
187186
render(DataTableSearch);
188187

189188
allRowsRendered();

0 commit comments

Comments
 (0)