Skip to content

Commit

Permalink
Add new Flash module to handle sending flashes from components, and r…
Browse files Browse the repository at this point in the history
…eceiving them in LiveViews
  • Loading branch information
sevenseacat committed Mar 21, 2023
1 parent dbe9621 commit c6a8db7
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 2 deletions.
4 changes: 4 additions & 0 deletions lib/phoenix_liveview_flash_components_example_web.ex
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ defmodule PhoenixLiveviewFlashComponentsExampleWeb do
use Phoenix.LiveView,
layout: {PhoenixLiveviewFlashComponentsExampleWeb.Layouts, :app}

on_mount PhoenixLiveviewFlashComponentsExampleWeb.Flash

unquote(html_helpers())
end
end
Expand All @@ -62,6 +64,8 @@ defmodule PhoenixLiveviewFlashComponentsExampleWeb do
quote do
use Phoenix.LiveComponent

import PhoenixLiveviewFlashComponentsExampleWeb.Flash, only: [put_flash!: 3]

unquote(html_helpers())
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ defmodule PhoenixLiveviewFlashComponentsExampleWeb.FirstComponent do
end

def handle_event("click", _params, socket) do
{:noreply, put_flash(socket, :info, "First-level component button clicked!")}
{:noreply, put_flash!(socket, :info, "First-level component button clicked!")}
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ defmodule PhoenixLiveviewFlashComponentsExampleWeb.SecondComponent do
end

def handle_event("click", _params, socket) do
{:noreply, put_flash(socket, :info, "Second-level component button clicked!")}
{:noreply, put_flash!(socket, :info, "Second-level component button clicked!")}
end
end
18 changes: 18 additions & 0 deletions lib/phoenix_liveview_flash_components_example_web/live/flash.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
defmodule PhoenixLiveviewFlashComponentsExampleWeb.Flash do
import Phoenix.LiveView

def on_mount(:default, _params, _session, socket) do
{:cont, attach_hook(socket, :flash_receiver, :handle_info, &maybe_receive_flash/2)}
end

defp maybe_receive_flash({:put_flash, type, message}, socket) do
{:halt, put_flash(socket, type, message)}
end

defp maybe_receive_flash(_, socket), do: {:cont, socket}

def put_flash!(socket, type, message) do
send(self(), {:put_flash, type, message})
socket
end
end

0 comments on commit c6a8db7

Please sign in to comment.