Handling sending a message and updating a chat optimistically w/ LiveView

Hey everyone,

I’ve been working on this side project for a bit, and I’m trying to find a way to optimistically update the chat when sending a message. I want the person to be able to type and send a message without waiting to see the message update in the chat, ie: if there’s some sort of noticeable latency.

How best would I go about implementing this in live view? I think it’d be something involving JS hooks but I’m not too sure how it’d look to implement such a thing.

example:

Thank you in advance and for always answering!

So there’s a few things here:

First you need to hook onto the form submit before LV handles it, so you can pull the values from the form. That’s likely done with a submit event listener on the form – probably added via a hook. LV afaik listens for submit events on the whole document, so your handler should be executed first. At this point you should either add or already have a uuid for the message, to be sent to LV, so your server and client use the same identifiers per message.

Then you’ll need a hook around the list of messages, which has a state of sent, but not received messages. The submit event handler would dispatch the collected data of the form to this component. Whenever a message is received it’s added to the list of messages and rendered. On the update callback of the hook it will check all ids of messages rendered by the server side – removing the ones which are found from its state and rendering all remaining ones – either simply to the end or you keep track of “which message came before” to be able to interleave client and server rendered messages.

1 Like

I am not sure how much latency you can hide by doing this. It will add quite a bit of complexity and further more, different parties may see different order of the messages; it could be a source of misunderstanding.

Okay I’ll see if I can do this! Thank you!

I see what you mean but WhatsApp/Telegram/signal have indicators of when it has been sent, when it was received by server and when it was sent by everyone. I’m not expecting latency to be bad but I am expecting them to be able to interact and see their message on their can’t immediately because that is the standard.

For a planet scale chat, they have no choice but to take on the complexity. Do you?