LiveView: Trigger event on changeset change

Hello,

I have a form inside a LiveComponent. The form has several elements that trigger different events, which in turn update the changeset assign. The automatic re-rendering works fine, but I’d like another function to run before render, right after handle_event, to further update assigns.

My current workaround is to call this update function on every single handle_event (including on "validate", which is assigned to phx-change), but this feels very wrong (repetitive, error-prone) since what I really want is to “observe” changes to the changeset regardless of where the change came from and update other assigns based on that. Is it possible to do it?

Thanks in advance!

You could try send/2.

# livecomponent
send(self(), {:update, something})
# liveview
def handle_info({:update, x}, socket) do
  {:noreply, assign(socket, something: x)}
end
1 Like

Thank you! But I still have to call this function on every event, right? What I’m looking for is something DRYer, that is automatically called right before render, regardless of where the change to assigns came from.

you always have to return a socket, so you could wrap a function around that, like update(socket).
I’m not sure that’s a good idea though, probably not.