Liveview phx-click clears unrelated input fields

The programming model is broadly: events update server-side assigns, ui is update to template + server-side assigns. This is by design to keep the conceptual load down to a reasonable level. A button event handler changes server-side assigns, so the output will be re-rendered. If you look at the web-socket traffic you will see that only the count change is re-sent in the payload.

In terms of guidelines for understanding what will be re-rendered - if you change something client side that’s in a LiveView template, and that change isn’t captured server-side, expect it to be overwritten when something server-side is updated unless it’s marked to be ignored. There are very few exception to this (e.g. updating a text box that currently has the focus - for fun you could change your checkbox to a text input, insert a :timer.sleep(1000) into the increment event handler and see that if you jump straight back to the text box after clicking the increment button, the text doesn’t get overwritten.)

This clean re-rendering that may overwrite client side changes is actually what you want by default even if it isn’t intuitive. Multiple sources of update increase the unpredictability of the system and also the cognitive load to figure out what’s happening. Where there is a need to “escape” from this behaviour (e.g. JS libraries updating portions of the DOM client-side) there is the phx-update escape hatch. Again, you can fiddle around inspecting the client-side templates to see how that part is removed from client-side template.

In terms of the mechanics, the client-side DOM patching combines the updates with a copy of template cached on the client-side. If you want to take a look in more detail add a couple more assigns & events to update them, then inspect liveSocket.main.rendered in the browser. Take a look at the websocket payload and see how it is interleaved with the template held in liveSocket.main.rendered. Once it is interleaved with the update the whole node is replaced, so anything in the template that has been changed outside of LiveView will be replaced with it.

9 Likes