Live Chat Icon For mobile
Live Chat Icon

How do I push data and update the UI from the server to the browser in Blazor?

Platform: Blazor| Category: General

By calling the StateHasChanged() method in Blazor, you can receive notifications about state changes and trigger component re-rendering to push the changes to the browser using SignalR. An example that illustrates this functionality is the Counter component. In this example, the component automatically pushes incremented count data using the Timer function and updates the UI in the browser by invoking the StateHasChanged() method within 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

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.