htmx
htmx copied to clipboard
Add `hx-swap` support to `hx-ext="sse"`
Hi there, I've testing sse extension in my project and it's working as expected for swapping the content. However, I want to add new message below like chat message. And when I tried hx-swap
with hx-target
but that also seems to update the target instead of appending it.
<div hx-ext="sse" sse-connect="/search/{{ query.id }}/" sse-swap="message" hx-target="#result" hx-swap="beforeEnd">
Hang tight we are fetching your results.
<div id="result"></div>
</div>
![Screenshot 2022-02-26 at 1 04 16 PM](https://user-images.githubusercontent.com/6974101/155834642-4980fb7a-1390-45d3-b7b5-cec4fe8f6330.png)
I need the end result should be like append into each box.
<div hx-ext="sse" sse-connect="/search/{{ query.id }}/" sse-swap="message" hx-target="#result" hx-swap="beforeEnd">
Hang tight we are fetching your results.
<div id="result">
<div class="box></div>
<div class="box></div>
<div class="box></div>
<!-- As soon as new message arrives this result get appended.-->
</div>
</div>
Let me know if this possible with sse or any alternatives thanks.
I think this would also solve https://github.com/bigskysoftware/htmx/issues/784
Yes. Agreed. Without duplicating a whole lot of code, this would require that html publish a workable swap()
method for external scripts to use. So this depends on #255
any progress ?
+1! I have exactly the same use case. Perhaps using htmx for a chat app is not in scope, but it feels like this would be a reasonable new application of existing htmx concepts.
I've gotten htmx to work for for a chat app, but it takes some extra tinkering. The easiest thing for me to do is was to use the SSE as a hx-trigger
to load additional items whenever they were posted to the server. It's an extra round-trip, but it made my server logic a lot easier.
To add a little more info to this issue, we specifically need access to the internal swap()
function that I mentioned above. I'm still holding out hope that we can get this included in the htmx 2.0 design. This would solve outstanding issues with A LOT of extensions.
Also, in case it is not obvious (it was not to me!) htmx has support for appending SSE message content in the built-in SSE functionality (hx-sse attribute docs). To do that I did:
<div hx-sse="connect:/stream swap:message" hx-swap="beforeend"></div>
That will directly append the SSE message content to the inner div as messages are streamed in. No additional round-trip required.
I wasn't able to figure out a way to achieve the same functionality in the new SSE extension. Hopefully that's figured out before the 2.0 release!
That is weird. I am using the SSE extension and this works fine for me using hx-swap="beforeend"
. I am using htmx 1.9.6.