I'm developing a blazor webassembly app. I have the requirement to show current DateTime in my app. Here is how I achieved my requirement with pure C#.
@using System.Threading
<p>@CurrentDateTime</p>
@code {
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
new Timer(DateTimeCallback, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
}
private void DateTimeCallback(object state)
{
CurrentDateTime = DateTimeOffset.UtcNow.ToString("dd MMM yyyy hh:mm:ss tt");
StateHasChanged();
}
}
This gives the exact current time and gets updated every second. But I'm little bit worried on calling StateHasChanged() every second. Does it impact performance in long run? or I need to fallback to javascript to achieve this functionality? Please suggest your inputs.