Clarification about flash messages with LiveView


I’m working with LiveView and I have an issue with flash messages.

When I want to display a flash message after push_dispatch/2, it works fine. But when I want to display a message after push_redirect/2, I got two messages displayed simultaneously.

The first message displayed comes from my LiveView template:

<p class="alert alert-info"><%= live_flash(@flash, :info) %></p>

But the second message comes from my layout:

<p class="alert alert-info"><%= get_flash(@conn, :info) %></p>

My understanding is that when we change the LiveView with push_redirect/2 (here from my Edit LV to my Index LV), the flash message gets saved in the connection then passed to the second LiveView for display, which results in two messages displayed at the same time.

I can’t remove the live_flash/2 because I still need to display messages with push_patch/2, and I can’t remove the get_flash/2 because I need it to display messages from traditional controllers.

Is there a workaround to display only one message or am I missing something?

Thank you :slight_smile:



The workaround is to have two separate templates, app.html with get_flash(@conn, ...) and live.html with live_flash(@flash, ...). might be useful. Also check out templates/layout/* in a fresh phoenix project generated with mix --live.


Thanks for your reply. I added a live.html template, but the problem remains.

It displays the flash message once correctly when I use push_redirect, but when I use push_patch nothings is displayed.

I hote it’s not too late, on your layout you can use

Map.get(@conn.assigns, :live_module)

For live view it will return the module that manage the live view. Otherwise you’ll get nil.

So in your layout you can do something like

<%= unless Map.get(@conn.assigns, :live_module) do %>
  <%= get_flash(@conn, :info) %>
<% end %>