Feature

Pretty notifications with LiveView and Alpine

Preview

This feature is about displaying in app notifications with Phoenix LiveView, Tailwind and AlpineJS.

I wanted to support multiple notifications and not just have a single flash message. I also wanted them to be nicely animated. That is why I needed to use a little javascript with Alpine JS.

Note that in a real app, I would set up the component to subscribe to a pubsub event.

lib/phoenix_features_web/live/components/notifications_simple.ex
defmodule PhoenixFeaturesWeb.Components.NotificationsSimple do
  use PhoenixFeaturesWeb, :live_component

  alias PhoenixFeatures.Notifications

  @impl true
  def mount(socket) do
    {:ok,
      socket
      |> assign(:notifications, [])
    }
  end

  @impl true
  def handle_event("notify", _, socket) do
    notification = Notifications.create_notification(%{})
    notifications = socket.assigns.notifications ++ [notification]

    {:noreply, assign(socket, notifications: notifications)}
  end

  @impl true
  def handle_event("clear", %{"id" => id}, socket) do
    notifications =
      socket.assigns.notifications
      |> Enum.filter(& &1.id == id)

    {:noreply, assign(socket, notifications: notifications)}
  end
end