Turbo Stream updating DOM inconsistently upon broadcast from model

I’m trying to update a certain element on the page when I delete another element, and I want to do that without reloading the entire page, so I figured Turbo Streams might be a good idea. I wanted to try out broadcasting from the model, so I added a callback there (this is for a model an object of which gets deleted):

after_destroy_commit { broadcast_update_to "stats", partial: "shared/stats", locals: { user: user }, target: "user-stats" }

I’m also rendering that stats partial on my index page. I subscribe to the stats turbo stream at the top of index.html.erb:

<%= turbo_stream_from "stats" %>

And I’m rendering the stats partial inside a div with id="user-stats":

<div id="user-stats">
  <%= render 'shared/stats', user: find_user %>

And it works! Sometimes.

When I delete a record, I can see the stats update in real time, without having to manually refresh the page. And then I do refresh the page manually, and then I add another record and try to delete it… and the counter doesn’t update in real time. I check the console: the correct partial with the updated stats does get sent to the stream ([ActionCable] Broadcasting to stats: "<turbo-stream action=\"update\" target=\"user-stats\"><template>..., and the HTML is correct), but the stats themselves don’t change.

What changes upon a page refresh, then, for everything to stop working? Why does it work the first time, but not after a manual page refresh? The stream ID is a string, so it remains the same, the value of the user passed as a local does not change, the target is a div with a hardcoded string as an ID, so that doesn’t change either. What am I doing wrong?

I’m not sure whats going wrong! although I see you are using “stats” as the turbo-stream identifier which would mean your broadcasts get sent to every user viewing this page for every new record. Not sure if this is what you were expecting but if you want to only broadcast new records to the user who created them you could change the turbo-stream?? not sure if this would help though.
If you want to share the content of the ‘shared/stats’ partial it might help me determine the issue

Possible troubleshooting steps: Look at the websocket connection from the browser developer tools and confirm that the browser receives the partial via websockets. Determine if the browser lost/closed the websocket connection.

There’s nothing much to that partial, just the user’s name and a counter, which is updated correctly in the model itself, but is not updated on the page. Changing the name of the turbo stream doesn’t do anything, either, I’m afraid.