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 %>
</div>
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?