DataTable: onCustomSaveState() called twice when globalFilter updated

UI Components for React
Post Reply
liamoshea
Posts: 7
Joined: 15 Jan 2021, 20:32

08 Feb 2021, 19:53

I'm encountering an issue wherein onCustomSaveState is called twice each time I modify the input to the global filter in the Data Table. In my application I am saving the state to a record in the database, so this behavior is undesired as it causes unnecessary calls to my backend.

The first time onCustomSaveState is called, the state object is as it was before the Global Filter input was altered. The second time it is called, the state object reflects the current (changed) state of the Global Filter input. For example if the filter is initially set to "hello worl" and I add a d to filter for "hello world", the first call shows the state as "hello worl" and the second call shows the state as "hello world"


Sample Code

Code: Select all

export default function DataTableFilter () {
  const [customers, setCustomers] = useState(data);
  const [globalFilter, setGlobalFilter] = useState(null);
   

  const onCustomSaveState = (state) => {
    console.log("I was run")
    console.log(state.filters?.globalFilter?.value)
    window.sessionStorage.setItem('dt-state-demo-custom', JSON.stringify(state));
  }

  const onCustomRestoreState = () => {
    return JSON.parse(window.sessionStorage.getItem('dt-state-demo-custom'));
  }

  
  const header = (
    <div className="table-header">
      List of Customers
      <span className="p-input-icon-left">
        <i className="pi pi-search" />
        <InputText type="search" onInput={(e) => setGlobalFilter(e.target.value)} placeholder="Global Search" />
      </span>
    </div>
  );

  return (
    <div className="datatable-filter-demo">
      <div className="card">
        <DataTable ref={dt} value={customers} paginator rows={10}
          header={header} className="p-datatable-customers"
          globalFilter={globalFilter} emptyMessage="No customers found."
          stateStorage="custom" customSaveState={onCustomSaveState} customRestoreState={onCustomRestoreState}
          >
          {/* My Column components here... */}
        </DataTable>
      </div>
    </div>
  );
}

Here is the output in the console after typing a "d" to complete "hello world"
Image

Thanks and appreciation,

- Liam

Post Reply

Return to “PrimeReact”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 1 guest