From d79f141707f146a32a1e07476a2d614785d00c6c Mon Sep 17 00:00:00 2001 From: shiibe <82057235+shiibe@users.noreply.github.com> Date: Wed, 5 Jun 2024 21:00:24 -0400 Subject: [PATCH] Search when input value changes --- TaikoWebUI/Pages/Users.razor | 2 +- TaikoWebUI/Pages/Users.razor.cs | 27 ++++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/TaikoWebUI/Pages/Users.razor b/TaikoWebUI/Pages/Users.razor index 62ab57f..b739d0b 100644 --- a/TaikoWebUI/Pages/Users.razor +++ b/TaikoWebUI/Pages/Users.razor @@ -10,7 +10,7 @@ @if (!AuthService.LoginRequired || (AuthService.LoginRequired && AuthService.IsAdmin)) { - + @if (isLoading || response == null) { diff --git a/TaikoWebUI/Pages/Users.razor.cs b/TaikoWebUI/Pages/Users.razor.cs index 3688b96..8cc1453 100644 --- a/TaikoWebUI/Pages/Users.razor.cs +++ b/TaikoWebUI/Pages/Users.razor.cs @@ -4,6 +4,7 @@ public partial class Users { private UsersResponse? response = new(); + private CancellationTokenSource? cts; private int TotalPages { get; set; } = 0; private bool isLoading = true; private int currentPage = 1; @@ -39,11 +40,35 @@ public partial class Users currentPage = page; await GetUsersData(); } + + private async Task Debounce(Func action, int delayInMilliseconds) + { + // Cancel the previous task + cts?.Cancel(); + + // Create a new CancellationTokenSource + cts = new CancellationTokenSource(); + + try + { + // Wait for the delay + await Task.Delay(delayInMilliseconds, cts.Token); + + // Execute the action + await action(); + } + catch (TaskCanceledException) + { + // Ignore the exception + } + } private async Task OnSearch(string search) { searchTerm = search; currentPage = 1; - await GetUsersData(); + + // Debounce the GetUsersData method + await Debounce(GetUsersData, 500); // 500 milliseconds delay } } \ No newline at end of file