I need dynamic updation of DOM value by using timer of every second.
I have tried a counter value increment on every second. But in that code, I have get an only the final value of that DOM value. I need every second value in my DOM.
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="StartLiveUpdate">Click me</button>
<button class="btn btn-primary" @onclick="StopLiveUpdate">Stop</button>
@code {
private static System.Timers.Timer syncTimer;
Random random = new Random();
void StartLiveUpdate()
{
syncTimer = new System.Timers.Timer(1000);
syncTimer.Elapsed += IncrementCount;
syncTimer.AutoReset = true;
syncTimer.Enabled = true;
}
void StopLiveUpdate()
{
syncTimer.Enabled = false;
syncTimer.Stop();
}
int currentCount = 0;
void IncrementCount(Object source, System.Timers.ElapsedEventArgs e)
{
currentCount++;
this.StateHasChanged();
}
}
Running the code above i get the following exception, thrown in the IncrementCount function:
System.InvalidOperationException: 'The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution to the Dispatcher when triggering rendering or component state.'
Passing the StateHasChanged call to InvokeAsync solves this:
InvokeAsync(this.StateHasChanged);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With