Hotwire Discussion

Solving the double append problem

In the intro video on https://hotwire.dev/, DHH runs into the double append problem when he introduces stream updates over ActionCable (websocket): the user who posts in chat see their new message twice since it’s appended once through the form submission response and once over the websocket.

He solves the problem by removing the append from the form submission response.

This means that if the user who posts in chat isn’t connected to the websocket, they won’t see their new message at all.

Have you found any general solution to this problem that doesn’t have the same drawback?

Hi,

A solution is to render a turbo_stream response to replace/update/reset the form (using for example a create.turbo_stream.erb), and not the message, then broadcast, over websocket, a turbo append tag. for all users including the author

If you ask what about some actions like edit or destroy to be accessible to message’s author and not other user, then just add those action in the message tag, as hidden of course, and with a stimulus js controller that check if it’s the current user or not (you can set a meta that reference the current user id for this kind of purpose in the head of your template); if the current user is the author then un-hide the action’s tag.

The bmol is that the user who post the message will get this message print like other and maybe the socket could take a little time … but the advantage is that it’s simple.

Cordialement,

I’ve been taking a crack at this in [RFC] Add remove_if_present to append and prepend (avoids double-insert) by jeromecornet · Pull Request #153 · hotwired/turbo-rails · GitHub

Feel free to chime in on this approach

1 Like