Only render static content in LiveView given a condition in mount

Hi!

Could I cancel the socket connection when a condition is met in mount?
In those cases, I would like mount to only be called once and render static content.

I had a look at the functions of LiveView [1] but I didn’t see any that fits.
Is it possible to do it? Could you point me to the right direction to do it?

Thank you!
[1] Phoenix.LiveView — Phoenix LiveView v0.16.3

You could have an assign based value in the page that your javascript looks for. If that value is present, you can simply not instantiate the LiveSocket object.

3 Likes

Thank you Ben!

Maybe it’s a trivial question but how could I read an assign value from app.js?

I know I can send a message from LiveView to the client with push_event/3 and had a look at [1] but I didn’t see how to access assigns from app.js.

Any help would be great. Thanks!
[1] JavaScript interoperability — Phoenix LiveView v0.16.3

You don’t access the assign directly, rather you put an element in the DOM that is derived from the value of the assign eg:

<div id="live-flag" data-should-be-live="<%= @should_be_live %>"></div>

Then in your javascript you can document.getElementById("#live-flag").dataset["should-be-live"] (or something like that) to fetch its value.

4 Likes

Makes sense, thank you!

Instead of .dataset, .getAttribute("should-be-live" == "true") works for me

1 Like