C#C
C#3y ago
Thinker

❔ Best way to display a continually updating list of messages

@inject MerpieClient Client
@inject MerpieHubConnection HubConnection
@inject ILogger<MessageList> Logger

<div class="flex flex-col-reverse gap-y-4">
    @foreach (var message in messages)
    {
        <MessageDisplay Message="message"/>
    }
</div>

@code {

    private readonly List<MessageDto> messages = new();

    protected override async Task OnInitializedAsync()
    {
        await HubConnection.StartConnection();

        HubConnection.OnMessageSent += OnMessageSent;
        HubConnection.OnMessageDeleted += OnMessageDeleted;
        HubConnection.OnMessageEdited += OnMessageEdited;
        
        // Fetch messages
        if (await Client.GetMessages() is ApiResult<IEnumerable<MessageDto>>.Success success)
            messages.AddRange(success.Value);
    }

    private void OnMessageSent(MessageDto message)
    {
        Logger.LogInformation("Message with ID {id} received", message.Id);
        
        messages.Insert(0, message);
        StateHasChanged();
    }

    private void OnMessageDeleted(MessageDto message)
    {
        Logger.LogInformation("Message with ID {id} deleted", message.Id);
        
        messages.Remove(message);
        StateHasChanged();
    }

    private void OnMessageEdited(MessageDto oldMessage, MessageDto newMessage)
    {
        Logger.LogInformation("Message with ID {id} edited", oldMessage.Id);

        messages[messages.IndexOf(oldMessage)] = newMessage;
        StateHasChanged();
    }

}

This is a component in a Blazor WASM chat app I'm developing which job is to display a list of messages. However I'm wondering whether this is an alright-ish way to go about keeping a continually updating list of messages, because to me it feels a bit iffy. Especially the fact I have this Remove call which has to iterate through all the messages to remove it. I don't know how well this would scale or whether there is a better approach.
Was this page helpful?