How would you implement real-time UI updates in a Blazor Server component in response to a backend event, like a new order being placed elsewhere in the system?
Short answer
Since Blazor Server components already maintain a live SignalR connection, you can inject a shared notification service (or use SignalR's own hub broadcasting, or an in-process event/message bus) that a component subscribes to on initialization, calling StateHasChanged() when a…
Advertisement
AModel answer
Since Blazor Server components already maintain a live SignalR connection, you can inject a shared notification service (or use SignalR's own hub broadcasting, or an in-process event/message bus) that a component subscribes to on initialization, calling StateHasChanged() when a relevant event arrives to trigger a re-render reflecting the new state -- effectively piggybacking real-time updates on Blazor Server's already-persistent connection without needing a separate polling mechanism.
public partial class OrderDashboard : IDisposable {
[Inject] private OrderNotificationService Notifier { get; set; }
protected override void OnInitialized() => Notifier.OrderPlaced += OnOrderPlaced;
private void OnOrderPlaced(Order order) {
orders.Add(order);
InvokeAsync(StateHasChanged); // triggers a UI re-render from a non-UI thread
}
public void Dispose() => Notifier.OrderPlaced -= OnOrderPlaced;
}Real-world example
A live order dashboard updates instantly across every connected admin's browser the moment a new order is placed anywhere in the system, using Blazor Server's existing SignalR connection combined with an in-process event subscription rather than requiring polling or a separate WebSocket implementation.
Likely follow-ups
- Why must StateHasChanged be called via InvokeAsync when triggered from a background event?
- How would this pattern differ for Blazor WebAssembly, which lacks a persistent server connection?
Related topics