Blazor

How do you manually trigger data or UI changes?

How do you manually trigger data or UI changes?

By default, Blazor detects changes and reflects them in the UI automatically. However, there might be a situation where we have to manually trigger changes. StateHasChanged informs the component that its state has changed, but it does not render the component. The component will decide when to render itself.

You can’t do that in a synchronous method, so you should async your code to give the component a chance to render.

@page "/"
  
 @using System.Threading;
  
 <button type="button" @onclick="@PlaceOrder_Clicked" disabled="@DisablePlaceOrderButton">@Title</button> 
@code{
     private bool DisablePlaceOrderButton { get; set; } = false;
  
     public string Title { get; set; } = "Click Button";
  
     private async Task PlaceOrder_Clicked()
     {
  
         await DisablePlaceOrder();
         DisablePlaceOrderButton = false;
         Title = "State Has Changed";
  
     }
  
     async Task DisablePlaceOrder()
     {
         DisablePlaceOrderButton = true;
         Title = "Wait...";
         await Task.Delay(3000);
  
         StateHasChanged();
     }
 } 
Sumitra Kumari Shaw

An Engineering graduate who Enjoys building things that live on the internet.