Calling the StateHasChanged() method in Blazor, you can be notified that the state has been changed and re-render the components to push their changes to the browser using SignalR. The following example demonstrates how the Counter component is pushing the increment count data automatically using the Timer function and updating the UI in the browser by calling the StateHasChanged() method in the InvokeAsync action.
[Counter.razor]
@page "/counter"
@using System.Timers
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private Timer time;
private void IncrementCount()
{
currentCount++;
}
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
time = new Timer();
//Set the time interval.
time.Interval = 1000;
time.Elapsed += OnTimeInterval;
time.AutoReset = true;
// Start the timer.
time.Enabled = true;
}
base.OnAfterRender(firstRender);
}
Private async void OnTimeInterval(object sender, ElapsedEventArgs e)
{
IncrementCount();
await InvokeAsync(() => StateHasChanged());
}
public void Dispose()
{
// While navigating to other components, Dispose method will be called and clean up the Timer function.
time?.Dispose();
}
}
Refer to this link for more details.
Share with