Deleting a Resource

Listing Cats

NameColorOwnerCategory Actions
Marley Black Brian Real
MJ Tortoiseshell Brian Real
Mr. Business Gray Gayle Fictional
Garfield Orange Jon Fictional
Goose Orange Wendy Fictional

Documentation:

https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#stream/4

https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#stream_delete/3

NOTE: reference the Setup section for generating the Animals context and adding the Cats to the database used in this example.

NOTE: while you can click the "Delete" link here and the cat will disappear, deleting cats is disabled for this preview and the cat will return on the next page mount. The code below will still delete cats.

scope "/", LiveViewBasicsWeb do
  pipe_through :browser

  live "/cats", CatLive.Index, :index
end
defmodule LiveViewBasicsWeb.CatLive.Index do
  use LiveViewBasicsWeb, :live_view

  alias LiveViewBasics.Animals

  def mount(_params, _session, socket) do
    socket = stream(socket, :cats, Animals.list_cats())
    {:ok, socket}
  end

  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash}>
      <h1 class="text-4xl font-bold text-center">Deleting a Resource</h1>
      <.header>
        Listing Cats
      </.header>
      <div class="mb-2">
        <.table
          id="cats"
          rows={@streams.cats}
        >
          <:col :let={{_id, cat}} label="Name">{cat.name}</:col>
          <:col :let={{_id, cat}} label="Color">{cat.color}</:col>
          <:col :let={{_id, cat}} label="Owner">{cat.owner}</:col>
          <:col :let={{_id, cat}} label="Category">{cat.category}</:col>
          <:action :let={{id, cat}}>
            <.link
              phx-click={JS.push("delete", value: %{id: cat.id}) |> hide("##{id}")}
              data-confirm="Are you sure?"
            >
              Delete
            </.link>
          </:action>
        </.table>
      </div>
    </Layouts.app>
    """
  end

  def handle_event("delete", %{"id" => id}, socket) do
    cat = Animals.get_cat!(id)
    {:ok, _} = Animals.delete_cat(cat)

    {:noreply, stream_delete(socket, :cats, cat)}
  end
end
# The below functions already exist if you ran the context generator in the Setup
def list_cats do
  Repo.all(Cat)
end

def get_cat!(id), do: Repo.get!(Cat, id)

def delete_cat(%Cat{} = cat) do
  Repo.delete(cat)
end