material-table icon indicating copy to clipboard operation
material-table copied to clipboard

Server side filtering with onFilterChange function.

Open hungbang opened this issue 7 years ago • 20 comments

I am using Reactjs and Material Table, I want to handle server-side filtering with actions and reducers, the table data which is stored on redux store will be updated every time filter event is called, then the table data is updated as well. I don't want to use Remote data because it doesn't apply redux cycle.

It would better if we have the custom event for filter

hungbang avatar Aug 13 '19 05:08 hungbang

Sounds like we have the same/similar issue but for searching:

https://github.com/mbrn/material-table/issues/982

m5tt avatar Aug 13 '19 21:08 m5tt

Great! after spending 3 hours for research, I am temporary moving to another library that has the server-side filtering. In the meantime, I will continue following this issue.

hungbang avatar Aug 14 '19 02:08 hungbang

Hi @hungbang and @m5tt Please use version 1.49.0 example:

 <MaterialTable
     ...
     onSearchChange={(e) => console.log("search changed: " + e)}
     ...
  />

ekaradev avatar Aug 15 '19 12:08 ekaradev

Great! after spending 3 hours for research, I am temporary moving to another library that has the server-side filtering. In the meantime, I will continue following this issue.

what library?

EVRUSIN avatar Aug 15 '19 14:08 EVRUSIN

Hi @hungbang and @m5tt Please use version 1.49.0 example:

 <MaterialTable
     ...
     onSearchChange={(e) => console.log("search changed: " + e)}
     ...
  />

Thank you for your reply. is there callback method for filter change as well?

Update: I've updated the version to 1.49.0 and double-checking. The onSearchChange is working properly but there is no callback method for filtering.

hungbang avatar Aug 15 '19 16:08 hungbang

Great! after spending 3 hours for research, I am temporary moving to another library that has the server-side filtering. In the meantime, I will continue following this issue.

what library?

https://github.com/gregnb/mui-datatables

hungbang avatar Aug 15 '19 16:08 hungbang

Hi @hungbang and @m5tt Please use version 1.49.0 example:

 <MaterialTable
     ...
     onSearchChange={(e) => console.log("search changed: " + e)}
     ...
  />

Thank you for your reply. is there callback method for filter change as well?

Update: I've updated the version to 1.49.0 and double-checking. The onSearchChange is working properly but there is no callback method for filtering.

@hungbang @emrekara37 How were you able to get it working? Passing the prop exactly as he did above on version 1.49.0 does nothing.

ImOnMars avatar Aug 15 '19 18:08 ImOnMars

image

Hi @hungbang and @m5tt Please use version 1.49.0 example:

 <MaterialTable
     ...
     onSearchChange={(e) => console.log("search changed: " + e)}
     ...
  />

Thank you for your reply. is there callback method for filter change as well? Update: I've updated the version to 1.49.0 and double-checking. The onSearchChange is working properly but there is no callback method for filtering.

@hungbang @emrekara37 How were you able to get it working? Passing the prop exactly as he did above on version 1.49.0 does nothing.

hungbang avatar Aug 15 '19 23:08 hungbang

@hungbang Yes - according to this comment on this issue it is because the callback is disabled in some way when material table sees that you're using remote data, which is pretty absurd.

ImOnMars avatar Aug 15 '19 23:08 ImOnMars

@emrekara37 Do you plan to someway handle server-side filtering? The onSearchChange is not helping for this usecase.

simromm avatar Aug 18 '19 11:08 simromm

@emrekara37 is there any update for this?

hungbang avatar Aug 22 '19 05:08 hungbang

@emrekara37 is there any update for this?

zhohon avatar Sep 06 '19 07:09 zhohon

@mbrn, @emrekara37 - I'm trying to use your workaround found here with the custom Body component onFilterChanged behavior. I'm running into an issue though when trying to set state on my component in the event handler. Using a hook or a redux action causes the table to 'reset'? I type a filter and the event is handled, but as soon as the call is made that reaches out of the scope of the handler, the table clears. I get the behavior I'm looking for out of the onSearchChange event handler of MaterialTable component. Could you help me figure out how to get this workaround working, or let me know if there's something I could do to help you get onFilterChange implemented on the MaterialTable component?

here's my code:

components={{
    Body: bodyProps => (
	<MTableBody
		{...bodyProps}
		onFilterChanged={(columnId: number, value: string) => {
			// get column's fieldName
                        // get data whose prop has same value as filter

                        // redux action, tried using local hook for state as well
			props.setSummaryData(matchingRows); 

			bodyProps.onFilterChanged(columnId, value);
		}}
/>),
}}

and here's the behavior I'm seeing: filter-issue

If I remove the props.setSummaryData call, the table filters as expected.

I'm using v 1.52.0

seanmccay avatar Oct 25 '19 15:10 seanmccay

fixed my issue by using the remote data feature and then storing my columns in component state so that they don't reset when you type a filter.

code:

const [columns] = useState<Array<Column<ProposalModels.Proposal>>>([
		// a bunch of column objects
	]);

.......................................................................................................................

<MaterialTable
	columns={columns}
	data={async (query: Query<ProposalModels.Proposal>) => {
		console.log(query);
		let proposals = props.proposals.length > 0 ? props.proposals : await props.getProposals();
		if (!TextHelper.isEmptyOrWhitespace(query.search)) {
			proposals = proposals.filter(p => {
				let hasMatch = false;
				for (const property in p) {
					if (p.hasOwnProperty(property)) {
						const val = p[property] + '';
						hasMatch = val.toLowerCase().includes(query.search.toLowerCase());
						if (hasMatch) {
							break;
						}
					} else {
						continue;
					}
				}

				return hasMatch;
			});
		}

		if (query.filters.length > 0) {
			let filter: Filter<ProposalModels.Proposal>;
			for (filter of query.filters) {
				if (filter.column.field === undefined) {
					continue;
				}
				proposals = proposals.filter(p => {
					const thisVal = p[filter.column.field as string] as string;
					return thisVal.toLowerCase().includes(filter.value);
				});
			}
		}

		setSummaryData(proposals);

		return {
			data: proposals,
			page: query.page,
			totalCount: proposals.length,
		};
	}}
	// some other props
/>

seanmccay avatar Oct 30 '19 19:10 seanmccay

Would have preferred to have an onFilterChange event though... Oof.

seanmccay avatar Oct 30 '19 19:10 seanmccay

Maybe the best way is to customize the Toolbar

juliosilvacwb avatar Mar 11 '20 15:03 juliosilvacwb

use query.search if using remote-data

`function remoteData(query: Query): Promise<QueryResult> {

console.log(query);
return new Promise((resolve, reject) => {
  api({
    url: 'enderecos',
    params: {
      limit: query.pageSize,
      page: query.page + 1,
      search: query.search || ' ',
    },
  })
    .then((response) => {
      resolve({
        data: response.data.map((row: Row) => {
          const {
            rua, bairro, cep, cidade,
          } = row;
          return {
            rua, bairro, cep, cidade,
          };
        }),
        page: query.page,
        totalCount: Number(response.headers['x-total-count']),
      });
    })
    .catch((erro) => reject(erro));
});

}`

fabiosoliveira avatar Jun 15 '20 23:06 fabiosoliveira

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. You can reopen it if it required.

stale[bot] avatar Sep 13 '20 23:09 stale[bot]

this might help if you use custom filter component: const mainHeader = [ { field: 'field', title: 'Field', // defaultFilter: // your default value here in case you want to use it from redux store , filterComponent: ({ columnDef, onFilterChanged }) => { return ( <input type='text' onBlur={e => { onFilterChanged(columnDef.tableData.id, e.target.value) // update your data func to support params passed from tabelRef.onChange functions }} /> ) } } ]

ROSHANDBIT avatar Feb 12 '21 13:02 ROSHANDBIT

how to implement using enter and then triger to api?

MisterFredy avatar Jul 30 '21 08:07 MisterFredy