How to force LiveView to re-render a page?

I need to re-render page when LiveView receives a message:

def handle_info(%MyMessage{}, socket) do
  socket = force_render(socket)
  {:noreply, socket}
end

But there is no function like force_render.

One way would be to navigate to it again, thus forcing it to re-render.
You can use redirect/2 or push_redirect/2 (see: https://hexdocs.pm/phoenix_live_view/live-navigation.html)

Yes. And I’m using this solution at this moment.
But it seems so awkward, because it leads to an unnecessary re-creation of the LiveView process.

1 Like

I may not fully understand what you want to do then.
If you just want to refresh specific parts you can play with the assigns and set the assigns and then the elements attached would be forced to re-render.
Could you explain a bit more you problem?

The only reason to re-render the page is if its contents change. The contents of a LiveView are based on its assigns.
So the usual way to re-render a LiveView is to change the value in one of the assigns.

There are some situations in which ‘simply’ doing this might be not enough, such as when multiple callbacks might be triggered at the same time. An example I encountered recently was a phx-blur and phx-change on the same element which could be triggered in either order, sometimes leaving the HTML in an unsatisfactory state. That particular case was resolved by adding an extra field to the assigns which was toggled by these callbacks, forcing a re-render that way. More information on the LiveView issue tracker.

2 Likes

Try this hack. (boolean must be set on mount)

Page

<%= if @rerender? != nil do %> body <% end %>

Backend

def handle_info(%MyMessage{}, socket) do
   {:noreply, assign(socket, rerender?: !socket.assigns.rerender?)}
end