Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StateHasChanged not detecting changes first time

It seems that StateHasChanged() only triggers the re-render of the component after an await operation on a Task (found here).

So I want to use only StateHasChanged for re-rendering rather than using Task.delay or Task.Run.

Here is my code:

protected async Task ClearSearch()
        {
            SearchTestCoupon = new Mechanic.Shared.TestCouponSearch();
            IsBusy = true;
            TestCouponGroups = new List<Mechanic.Shared.TestCouponGroup>();
            StateHasChanged();  // << -------- **FIRST TIME** 
            //await Task.Delay(TimeSpan.FromSeconds(1));
            await GetTestCouponGroups(SearchTestCoupon);
        }

 protected async Task GetTestCouponGroups(object args)
        {
                TestCouponGroups = await TestCouponService.GetTestCouponGroupsAsync(SearchTestCoupon);
                IsRowSelected = false;
                IsBusy = false;
                StateHasChanged(); // << -------- **SECOND TIME**
        }

Here I use loader which is activate using IsBusy. But It is not working the first time when StateHasChanged is called as mentioned in the code.

But it renders component as expected the second time.

I have used Task.Delay but it is breaking my other functionalities like clearing grid and showing searched data etc.

like image 377
Aarsh Avatar asked Nov 06 '22 09:11

Aarsh


1 Answers

StateHasChanged doesn't re-render the component, the component re-render when events delegates (OnClick, OnMouseMouve...) finished.

So in your case, if you want to re-render the component on the first StateHasChanged your code should be :

protected void ClearSearch()
        {
            SearchTestCoupon = new Mechanic.Shared.TestCouponSearch();
            IsBusy = true;
            TestCouponGroups = new List<Mechanic.Shared.TestCouponGroup>();            
            GetTestCouponGroups(SearchTestCoupon); // don't await 
            StateHasChanged();  // << -------- **FIRST TIME** 
        }

 protected async Task GetTestCouponGroups(object args)
        {
                TestCouponGroups = await TestCouponService.GetTestCouponGroupsAsync(SearchTestCoupon);
                IsRowSelected = false;
                IsBusy = false;
                StateHasChanged(); // << -------- **SECOND TIME**
        }
like image 90
agua from mars Avatar answered Nov 12 '22 19:11

agua from mars