Reputation: 188
I need a way to debounce an event emitted by clarity datagrid so that I only fetch data from back end after user has finished typing. I'm using the grid within an angular 6 application and bind the event to my function. My setup is as follows,
<clr-datagrid (clrDgRefresh)="fetchData($event)"></clr-datagrid>
fetchData(state) {
// Fetch data from back end
}
How do I debounce the event so it does not trigger my fetchData function on each keyup? I don't have a handle to any of the datagrids filter inputs neither do I know how many inputs there will be. All I have is an event that is triggered when there's a key up on any of the grid filter inputs.
Upvotes: 0
Views: 967
Reputation: 1808
You can debounce the events on the app side with the rxjs operator debounceTime
debouncer = new Subject<any>();
refresh(state: ClrDatagridStateInterface) {
this.debouncer.next(state);
}
this.debouncer.asObservable().pipe(
debounceTime(2000)
).subscribe(state => {
this.loading = true;
const filters: { [prop: string]: any[] } = {};
if (state.filters) {
for (const filter of state.filters) {
const { property, value } = <{ property: string; value: string }>filter;
filters[property] = [value];
}
}
this.inventory
.filter(filters)
.sort(<{ by: string; reverse: boolean }>state.sort)
.fetch(state.page.from, state.page.size)
.then((result: FetchResult) => {
this.users = result.users;
this.total = result.length;
this.loading = false;
});
})
This is a quick POC so obviously it could also be typed for the datagrid state interface or improved in other ways (such as more rxjs operators to handle other use cases). Besides that, it should give you an idea on how datagrid events could be debounced by that app.
Here is a working POC on stackblitz.
Upvotes: 4