Is there any way to consume a stream more than once in a LiveView? The stream comes with a DOM id, so if I use it in multiple places as-is, I’ll get elements with the same id. My use case is I’m rendering an item in a list and in a map as well.
Thanks!
1 Like
I just gave this a try and it seemed to work. I rendered the stream once as normal:
<div phx-update="stream" id="stream-1">
<ul>
<li :for={{dom_id, item} <- @streams.items} id={dom_id}>
<%= item.name %>
</li>
</ul>
</div>
Then to render the same stream again I appended a character to the dom_id
to ensure it was unique.
<div phx-update="stream" id="stream-2">
<ul>
<li :for={{dom_id, item} <- @streams.items} id={dom_id <> "2"}>
<%= item.name %>
</li>
</ul>
</div>
This isn’t officially documented anywhere so its s possible it could break in a future release.
I’d be interested to hear if any others with more knowledge of the LiveView internals could advise if this is a bad idea.
3 Likes
Unfortunately this breaks. See Phoenix.LiveView — Phoenix LiveView v0.20.14. It mentions it requires the ‘dom_id’ and only it.
I went through problems with this recently, created an app to reproduce and opened an issue but looks like this is not how it’s supposed to be used.
Ended up using two streams.
4 Likes
Ah, good to know. It felt like a bit of an edge case, but also creating duplicate streams felt like a pretty crazy workaround.
Thanks everyone!
1 Like