Why won't my edit functionality work?

Hello all! I’m currently making a todo list app with Phoenix, Elixir and Postgres following this tutorial. For some reason, I’m having an issue assigning the values of the last two inputs on the code below.

I followed the code from the tutorial but honestly the tutorial is a little dated. Let me know!

defmodule TodoListAppWeb.PageLive do
  use TodoListAppWeb, :live_view
  alias TodoListApp.Todos

  def mount(_params, _session, socket) do
    items = Todos.list_items()
    {:ok, assign(socket, items: items, editing: %{id: 0, name: ""})}
  end

  ## when we create a new item, the done state is false
  def handle_event("create_item", %{"name" => name}, socket) do
    with {:ok, new_item} <- Todos.create_item(%{name: name, done: false}) do
      items = get_items(socket)
      items = [new_item | items]

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

  ## delete item
  def handle_event("delete_item", %{"id" => id}, socket) do
    IO.puts("~~~~~~~~~~ID~~~~~~~~~~~~~~")
    IO.puts(String.to_integer(id))
    IO.puts("~~~~~~~~~~~~~~~~~~~~~~~~")

    items = get_items(socket)
    item = get_item_by_id(items, id)

    with {:ok, deleted_item} <- Todos.delete_item(item)  do
      items = filter_item(items, deleted_item)

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

  def handle_event("update_editing", %{"id" => id}, socket) do
    items = get_items(socket)
    editing = get_item_by_id(items, id)

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

  defp filter_item(items, deleted_item) do
    Enum.filter(items, fn item -> item.id !== deleted_item.id end)
  end

  defp get_item_by_id(items, id) do
    Enum.find(items, fn item -> item.id == String.to_integer(id) end)
  end

  defp update_item(items, new_item) do
    Enum.map(items, fn item ->
      if item.id == new_item.id do
        new_item
      else
        item
      end
    end
    )
  end

  defp get_items(socket) do
    socket.assigns.items
  end

  def render(assigns) do
    ~H"""
    <form class="create-form" phx-submit="create_item">
    <input type="text" name="name" placeholder="Add a new task!"/>
    <button>Add</button>
    </form>

    <%= for item <- @items do %>
    <p><%= item.id %></p>
    <p><%= item.name %></p>
    <button phx-click="delete_item" phx-value-id={item.id}>Delete</button>
    <button phx-click="update_editing" phx-value-id={item.id}>Edit</button>
    <% end %>

    <div>
      <p>What would you like to update the data with??</p>
      <input type="number" value={editing.id}/>
      <input type="text" value={editing.name}/>
    </div>
    """
  end
end```

Looks like you’re just missing a @: @editing, not editing.

2 Likes

This worked! Thank you!

1 Like