I need to listen to a method in signalR and update the UI when this happens. Data is coming but UI is not updating
here is my code:
@foreach (var user in users)
{
<MudItem xs="12" md="6">
<MudCard>
<h3>@user.FirstName @user.LastName</h3>
</MudCard>
</MudItem>
}
@code {
List<UserDto> users = new();
HubConnection connection = new HubConnectionBuilder()
.WithUrl("ws://localhost:6172/chat")
.Build();
protected override async Task OnInitializedAsync()
{
connection.On<UserDto>("UserJoined", async (user) =>
{
users.Add(user);
await InvokeAsync(StateHasChanged);
});
await connection.StartAsync();
}
}
If I try to use the StateHasChanged() method like below I get an exception:
connection.On<UserDto>("UserJoined", async (user) =>
{
users.Add(user);
StateHasChanged();
});
Exception:
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.'