5

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Aarsh
  • 2,555
  • 1
  • 14
  • 32

1 Answers1

1

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**
        }
agua from mars
  • 16,428
  • 4
  • 61
  • 70
  • It worked for me ! but still I am using async method and I should call await for that method.So I don't understand what happened there but it worked. can you explain it in answer ? – Aarsh Mar 12 '20 at 06:17
  • 1
    Because the component is render when it exits the method. if you await it will be re rendered after `GetTestCouponGroups`finished. – agua from mars Mar 12 '20 at 07:47