Browse Source

fix(dashboard): Set data table page to 1 when filter term changes

Michael Bromley 3 months ago
parent
commit
7e9329d6d9
1 changed files with 9 additions and 1 deletions
  1. 9 1
      packages/dashboard/src/lib/components/data-table/data-table.tsx

+ 9 - 1
packages/dashboard/src/lib/components/data-table/data-table.tsx

@@ -29,7 +29,7 @@ import {
     VisibilityState,
     VisibilityState,
 } from '@tanstack/react-table';
 } from '@tanstack/react-table';
 import { RowSelectionState, TableOptions } from '@tanstack/table-core';
 import { RowSelectionState, TableOptions } from '@tanstack/table-core';
-import React, { Suspense, useEffect } from 'react';
+import React, { Suspense, useEffect, useRef } from 'react';
 import { AddFilterMenu } from './add-filter-menu.js';
 import { AddFilterMenu } from './add-filter-menu.js';
 import { DataTableBulkActions } from './data-table-bulk-actions.js';
 import { DataTableBulkActions } from './data-table-bulk-actions.js';
 import { DataTableProvider } from './data-table-context.js';
 import { DataTableProvider } from './data-table-context.js';
@@ -128,6 +128,7 @@ export function DataTable<TData>({
         defaultColumnVisibility ?? {},
         defaultColumnVisibility ?? {},
     );
     );
     const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});
     const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});
+    const prevSearchTermRef = useRef(searchTerm);
 
 
     useEffect(() => {
     useEffect(() => {
         // If the defaultColumnVisibility changes externally (e.g. the user reset the table settings),
         // If the defaultColumnVisibility changes externally (e.g. the user reset the table settings),
@@ -187,6 +188,13 @@ export function DataTable<TData>({
         onColumnVisibilityChange?.(table, columnVisibility);
         onColumnVisibilityChange?.(table, columnVisibility);
     }, [columnVisibility]);
     }, [columnVisibility]);
 
 
+    useEffect(() => {
+        if (page && page > 1 && itemsPerPage && prevSearchTermRef.current !== searchTerm) {
+            onPageChange?.(table, 1, itemsPerPage);
+            prevSearchTermRef.current = searchTerm;
+        }
+    }, [onPageChange, searchTerm]);
+
     const visibleColumnCount = Object.values(columnVisibility).filter(Boolean).length;
     const visibleColumnCount = Object.values(columnVisibility).filter(Boolean).length;
 
 
     const handleSearchChange = (value: string) => {
     const handleSearchChange = (value: string) => {